Thread.interrupted()
测试当前线程是否已经中断
public static boolean interrupted() {
return currentThread().isInterrupted(true);
}
调用:
Thread.currentThread().interrupt();
System.out.println("name :"+Thread.currentThread().getName()+" "+Thread.interrupted());
System.out.println("name :"+Thread.currentThread().getName()+" "+Thread.interrupted());
返回结果:
name :main true
name :main false
说明:该方法是测试当前线程是否中断,这里是指main,而且具有清除中断状态的效果
Thread.currentThread().isInterrupted()
测试线程Thread对象是否已经中断
public boolean isInterrupted() {
return isInterrupted(false);
}
测试:
Thread.currentThread().interrupt();
System.out.println("name :"+Thread.currentThread().getName()
+" "+Thread.currentThread().isInterrupted());
System.out.println("name :"+Thread.currentThread().getName()
+" "+Thread.currentThread().isInterrupted());
结果:
name :main true
name :main true
不清除中断状态,且,这个是测试调用该方法的对象的中断状态
Thread.currentThread().interrupt()
扫描二维码关注公众号,回复:
997541 查看本文章
如果该线程阻塞在调用wait()方法,join()或者sleep()方法, 他的中断状态将会被清除并且会抛出InterruptedException 如果该线程是阻塞在I/O操作(这个操作是在通道时期)这个通道将会被关闭,这个线程的中断状态 将会被设置,并且线程会接收到通道被中断关闭的异常,如果没有初始环境,这个线程的中断状态将会被设置
public void interrupt() {
if (this != Thread.currentThread())
checkAccess();
synchronized (blockerLock) {
Interruptible b = blocker;
if (b != null) {
interrupt0(); // Just to set the interrupt flag
b.interrupt(this);
return;
}
}
interrupt0();
}
</li>