java线程之中断interrupt详解

来源:互联网 发布:openwrt 进入webshell 编辑:程序博客网 时间:2024/06/01 10:00
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(1000);   // 休眠1秒               }catch(InterruptedException e){  // 退出阻塞态时将捕获异常                      System.out.println(getName()+"从阻塞态中退出...");                          this.interrupt();  // 改变线程状态,使循环结束               }          }          System.out.println(getName() + " 已经终止!");      }}public class Test{      public static void main(String argv[]) throws InterruptedException{             ThreadA ta = new ThreadA();              ta.setName("ThreadA");                ta.start();                Thread.sleep(20000);// 主线程休眠20秒,等待其他线程执行              System.out.println(ta.getName()+" 正在被中断.....");              ta.interrupt();  //  中断线程ThreadA      }}


 

输出:
ThreadA 将要运行...
ThreadA 运行中 0
ThreadA 运行中 1
ThreadA 运行中 2
ThreadA 运行中 3
ThreadA 运行中 4
ThreadA 运行中 5
ThreadA 运行中 6
ThreadA 运行中 7
ThreadA 运行中 8
ThreadA 运行中 9
ThreadA 运行中 10
ThreadA 运行中 11
ThreadA 运行中 12
ThreadA 运行中 13
ThreadA 运行中 14
ThreadA 运行中 15
ThreadA 运行中 16
ThreadA 运行中 17
ThreadA 运行中 18
ThreadA 运行中 19
ThreadA 正在被中断.....
ThreadA从阻塞态中退出...
ThreadA 已经终止!

看到输出结果后就应该完全明白了interrupt的用法了;总的来说:用isInterrupted检测中断,用interrupt()方法去中断!
原创粉丝点击