除了之前说的结束线程的方法,JDK有一种更强大的支持。interrupt();这个方法只是通知那个线程,有人想要你终止,终不终止你自己看着办。调用interrupt()。
/** * Created by li on 2016/11/24. */ public class DemoThread extends Thread { public static void main(String[] args) { DemoThread demoThread = new DemoThread(); demoThread.start(); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(1); demoThread.interrupt(); } @Override public void run() { while (!interrupted()) { // if (Thread.currentThread().isInterrupted()) { // System.out.println("终止"); // break; // } System.out.println("bulabulabula"); } } }
在另一个线程阻塞(eg:sleep)的同时终止这个线程,会报错。中断失败。sleep()在正常工作清空也不要用。