有感于线程中断的一个方法(原创)

前日研究Java线程问题,发现很多书上都没有提到interrput()方法,提到的也说用interrupt()方法无法实现线程中断,可是,经过我的不断尝试,竟然使用interrupt()方法和isInterrupted()方法实现了线程的中断,如果这个方法可以,那么除了使用共享变量的方式可以中断线程之外又多了一种中断线程的方法,希望这个方法对大家有所帮助。

class ThreadA extends Thread{
      int count = 0;
      public void run(){
          System.out.println(getName() + " 将要运行...");
          while (!this.isInterrupted()){
               System.out.println(getName() + " 运行中 " + count++);
               try{ 
                      Thread.sleep(400);                          // 休眠400毫秒
               }catch(InterruptedException e){                           // 退出阻塞态时将捕获异常
                      System.out.println(getName()+"从阻塞态中退出...");   
                      this.interrupt();                                      // 改变线程状态,使循环结束
               }
          }
          System.out.println(getName() + " 已经终止!"); 
    }
}
class ThreadDemo134{
      public static void main(String argv[]) throws InterruptedException{
             ThreadA ta = new ThreadA();
              ta.setName("ThreadA");  
              ta.start();  
              Thread.sleep(2000);                                          // 主线程休眠2000毫秒,等待其他线程执行
              System.out.println(ta.getName()+" 正在被中断.....");
              ta.interrupt();                                                                             //  中断线程ThreadA
      }
}

程序运行结果在相册中

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值