(48)21.4.4 检查中断---Java编程思想之并发笔记

21.4.4 检查中断
1.中断状态的设置
     通过用interrupted()来检查中断状态,这个不仅可以告诉你interrupt()是否被调用过,而且可以清除中断状态。清除中断状态可以确保并发结构不会就某个任务被中断这个问题通知你两次,你可以经由单一的InterruptedException或单一的成功的Thread.interrupted()测试来得到这种通知。
2.例子
package  jiangning.c21;

import  java.util.concurrent.TimeUnit;

class  NeedsCleanUp{
        private  final  int  id ;
        public  NeedsCleanUp( int  ident){
              this . id  = ident;
            System.  out .println( "NeedsCleanUp "  +  id );
      }
        public  void  cleanUp(){
            System.  out .println( "cleanUp "  +  id );
      }
}
class  Block3  implements  Runnable{
        private  volatile  double  d  = 0.0;
        public  void  run(){
              try  {
                    while (!Thread.interrupted()){
                          //point1
                        NeedsCleanUp n1 =  new  NeedsCleanUp(1);
                          try {
                              System.  out .println( "Sleeping"  );
                              TimeUnit.  SECONDS .sleep(1);
                                //point2
                              NeedsCleanUp n2 =  new  NeedsCleanUp(2);
                                try  {
                                    System.  out .println( "Calculating"  );
                                      for ( int  i=0;i<2500000;i++){
                                            d  =  d  + (Math.  PI  + Math. E )/ d ;
                                    }
                                    System.  out .println( "Finished time-consuming opration" );
                              }  finally  {
                                    n2.cleanUp();
                              }
                        }  finally {
                              n1.cleanUp();
                        }
                  }
                  System.  out .println( "Exiting while() test"  );
            }  catch  (InterruptedException e) {
                  System.  out .println( "Exiting via InterruptedException" );
            }
      }
}
public  class  InterruptingIdiom {

        public  static  void  main(String[] args)  throws  Exception {
              if (args. length  != 1){
                  System.  out .println( "usage: java InterruptingIdiom delay-in-mS" );
                  System. exit(1);
            }
            Thread t =  new  Thread( new  Block3());
            t.start();
            TimeUnit.  MILLISECONDS .sleep( new  Integer(args[0]));
            t.interrupt();
      }

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值