当我们创建一个线程循环打印语句时,我们想要发出一个指令让该线程停下来,此时,我们可以发送线程中断的命令
线程是否中断实际上是根据一个表示是否中断的标志位来决定的,这个标志位我们既可以自定义,也可以使用Thread内部的一个boolean变量来表示
class MyRunnable implements Runnable {public volatile boolean isQuit = false;@Overridepublic void run() {while (isQuit == false) {System.out.println("isQuit is false");}System.out.println("isQuit is true");}
}public class Demo15 {public static void main(String[] args) throws InterruptedException {MyRunnable myRunnable = new MyRunnable();Thread t = new Thread(myRunnable);t.start();Thread.sleep(100);myRunnable.isQuit = true;}
}
public class Demo {public static void main(String[] args) throws InterruptedException {Thread t = new Thread(()->{while (true) {System.out.println("hello");try {Thread.sleep(1000);} catch (InterruptedException e) {System.out.println(Thread.currentThread().isInterrupted());e.printStackTrace();System.out.println("thread is interrupted");break;}}});t.start();Thread.sleep(3000);t.interrupt();}
}
public class Demo {public static void main(String[] args) throws InterruptedException {Thread t = new Thread(()->{while (!Thread.interrupted()) {System.out.println("hello");}System.out.println(Thread.interrupted());});t.start();Thread.sleep(100);t.interrupt();}
}
public class Demo {public static void main(String[] args) throws InterruptedException {Thread t = new Thread(()->{while (!Thread.currentThread().isInterrupted()) {System.out.println("hello");}System.out.println(Thread.currentThread().isInterrupted());});t.start();Thread.sleep(100);t.interrupt();}
}
故线程收到通知的方式有两种: