使用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()+ " 正在被中断....."); //2000毫秒过去后,main拿到cpu控制权。
                        ta.interrupt();     //    中断线程ThreadA
        }
}
运行结果:
ThreadA 将要运行...
ThreadA 运行中 0
ThreadA 运行中 1
ThreadA 运行中 2
ThreadA 运行中 3
ThreadA 运行中 4
ThreadA 正在被中断.....
ThreadA从阻塞态中退出...
ThreadA 已经终止!

你可能感兴趣的:(thread,interrupt,isinterrupted)