Thread.interrupted()方法的陷阱

来源:互联网 发布:战网网络问题 编辑:程序博客网 时间:2024/05/17 01:16
  1. <strong><span style="font-size:16px;">package test84;  
  2.   
  3. public class selfInterrupt {  
  4.   
  5. public static void main(String[] args) {  
  6. Thread.currentThread().interrupt();  
  7. //  下面的判断会打印出来这样的语句 Interrupt:false  
  8. //  这样的结果是不是很让人费解呢???  
  9. //    
  10. //  分析其原因为:  
  11. //    
  12. //  因为在上面的一句代码可以中断线程,所以if判断线程是否中断就会得到的事true  
  13. //  但是 Thread.interrupted()这个方法执行完后就会清除线程的中断状态,  
  14. //  所以最后再次的打印Thread.interrupted()方法就会得到false结果。  
  15. if(Thread.interrupted())  
  16. System.out.println("Interrupted:"+ Thread.interrupted());  
  17. else  
  18. {  
  19. System.out.println("Not Interrupted"+Thread.interrupted());  
  20. }  
  21. //  如果用下面的这个方法来进行if判断就会出现那种情况了,  
  22. //  Thread.currentThread().isInterrupted();这个方法得到的结果:Interrupt:true  
  23. //    
  24. //  因为它判断完后就不会清除线程的中断状态,只是返回一个线程状态的结果  
  25. }  
  26. }</span></strong>  
0 0
原创粉丝点击