可以从不少博客中,可以得知Thread.interrupted(),可以清除当前线程的中断标志位,但是不知道清除之后有什么影响,
今天测试了下,中断标志位,就是一个线程是否要中断的标志。但是有以下规则
当线程正在执行时,线程被中断了,线程还会继续执行,不会中断,当线程在执行过程中遇到了wait()、sleep()、或者被其它线程join()时,才会处理中断,抛出一个中断异常。
假如在没有处理中断之前,程序执行了Thread.interrupted(),那么就会清除中断标志位,线程就不会再中断了。
1)、被清除中断标志位,程序能够正常执行
public static void main(String[] args) throws Exception {
Thread.currentThread().interrupt();
System.out.println("是否终止2? =" + Thread.interrupted());
System.out.println("是否终止2? =" + Thread.currentThread().isInterrupted());
Thread.sleep(500);
System.out.println("----------end-----------");
Lock lock = new ReentrantLock();
lock.lock();
}
执行结果:
是否终止2? =true
是否终止2? =false
----------end-----------
2)、没有清除中断标志位,程序抛中断异常
public static void main(String[] args) throws Exception {
Thread.currentThread().interrupt();
//System.out.println("是否终止2? =" + Thread.interrupted());
System.out.println("是否终止2? =" + Thread.currentThread().isInterrupted());
Thread.sleep(500);
System.out.println("----------end-----------");
Lock lock = new ReentrantLock();
lock.lock();
}
执行结果
Exception in thread "main" java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
是否终止2? =true
at com.cn.mail.lock.LockTest.main(LockTest.java:12)
Process finished with exit code 1