interrupt()、interrupted()、isInterrupted()区别
程序员文章站
2022-05-04 21:39:06
...
# 线程中断方法
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);
}
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);
}
推荐阅读
-
关于Java thread的interrupt, isInterrupt, interrupted
-
interrupt、interrupted、isInterrupted的区别
-
一个例子说明Thread interrupt() interrupted() isInterrupted()三个方法关系和区别
-
interrupt()、interrupted()、isInterrupted()区别
-
对Java中interrupt、interrupted和isInterrupted的理解
-
JAVA多线程之中断机制stop()、interrupted()、isInterrupted()
-
JAVA多线程之中断机制stop()、interrupted()、isInterrupted()
-
对Java中interrupt、interrupted和isInterrupted的理解
-
一个例子说明Thread interrupt() interrupted() isInterrupted()三个方法关系和区别
-
interrupt、interrupted、isInterrupted的区别