# 线程中断方法
interrupt()

# interrupt()方法中断后 第一次调用interrupted(),返回true
# 之后调用interrupted()返回false,除非线程重新中断
interrupted()


# interrupt()调用后,isInterrupted()返回true
isInterrupted()


demo1

# demo1

public static void main(String[] args) throws Exception{

Thread t = new Thread(() -> {

while (!Thread.currentThread().isInterrupted()){

System.out.println(Thread.currentThread().getName()+" "+Thread.currentThread().isInterrupted());

}

System.out.println("The End ! isInterrupted="+Thread.currentThread().isInterrupted());
System.out.println("The End ! isInterrupted="+Thread.currentThread().isInterrupted());
System.out.println("The End ! isInterrupted="+Thread.currentThread().isInterrupted());

});

t.start();

Thread.sleep(2000);

t.interrupt();

TimeUnit.SECONDS.sleep(60);

}


interrupt()、interrupted()、isInterrupted()区别_线程中断


demo2

public static void main(String[] args) throws Exception{

AtomicInteger atomicInteger = new AtomicInteger(0);

Runnable runnable = () ->{

while (true){
boolean interrupted = Thread.interrupted();
if(interrupted) {
atomicInteger.incrementAndGet();
System.out.println("============================"+Thread.currentThread().getName()+" "+interrupted);
}else {
if(atomicInteger.get()>0){
atomicInteger.incrementAndGet();
}
System.out.println("----------------------------"+Thread.currentThread().getName()+" "+interrupted);
if(atomicInteger.get()>5) break;
}

}

};

Thread t = new Thread(runnable);
t.start();

Thread.sleep(2000);
t.interrupt();

TimeUnit.SECONDS.sleep(60);

}


interrupt()、interrupted()、isInterrupted()区别_线程中断_02