


public class InterruptDemo{
static volatile boolean isStop = false;//方式1
static AtomicBoolean atomicBoolean = new AtomicBoolean(false);//方式2
/**
* 方式1:通过一个volatile变量实现
*/
public static void m1(){
new Thread(() -> {
while(true)
{
//通过监听中断标识自己结束线程(结束逻辑程序员自定义)
if(isStop)
{
System.out.println("-----isStop = true,程序结束。");
break;
}
System.out.println("------hello isStop");
}
},"t1").start();
//暂停几秒钟线程
try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
//其他线程修改中断表示
new Thread(() -> {
isStop = true;
},"t2").start();
}
/**
* 方式2:通过AtomicBoolean
*/
public static void m2(){
new Thread(() -> {
while(true)
{
//通过监听中断标识自己结束线程(结束逻辑程序员自定义)
if(atomicBoolean.get())
{
System.out.println("-----atomicBoolean.get() = true,程序结束。");
break;
}
System.out.println("------hello atomicBoolean");
}
},"t1").start();
//暂停几秒钟线程
try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
//其他线程修改中断表示
new Thread(() -> {
atomicBoolean.set(true);
},"t2").start();
}
/**
* 方式3:Thread类⾃带的中断API⽅法interrupt()
*/
public static void m3(){
Thread t1 = new Thread(() -> {
while (true) {
//通过监听中断标识自己结束线程(结束逻辑程序员自定义)
if (Thread.currentThread().isInterrupted()) {
System.out.println("-----isInterrupted() = true,程序结束。");
break;
}
System.out.println("------hello Interrupt");
}
}, "t1");
t1.start();
try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
//其他线程修改中断表示
new Thread(() -> {
t1.interrupt();//修改t1线程的中断标志位为true
},"t2").start();
}
}
1.线程调⽤interrupt()时:
2.中断只是⼀种协同机制,修改中断标识位仅此⽽已,不是⽴即stop打断。
3.sleep⽅法抛出InterruptedException后,中断标识也被清空置为false。如果我们在catch没有通过调用th.interrupt( )方法再次将中断标识位设置位true,这就是导致无限循环了。
public static void m5()
{
Thread t1 = new Thread(() -> {
while (true) {
if (Thread.currentThread().isInterrupted()) {
System.out.println("-----isInterrupted() = true,程序结束。");
break;
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
//线程的中断标志位重新设置为false,无法停下,需要再次掉interrupt()设置true
Thread.currentThread().interrupt();//???????
e.printStackTrace();
}
System.out.println("------hello Interrupt");
}
}, "t1");
t1.start();
try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); }
//其他线程修改中断表示
new Thread(() -> {
t1.interrupt();//修改t1线程的中断标志位为true
},"t2").start();
}