多线程编程<五>
1 /** 2 * 中断线程:当线程由于调用sleep(),join(),wait()而暂停时,如果中断它,则会收到一个InterruptedException异常。 3 * 调用Thread.isInterrupted(),Thread.interrupted()判断中断,Thread.interrupted()会重新设置线程的中断状态。 4 */ 5 public class InterruptDemo { 6 public static void main(String[] args) { 7 MyThread mt = new MyThread(); 8 MyThread mt2 = new MyThread(); 9 Thread thrd = new Thread(mt, "MyThread #1"); 10 Thread thrd2 = new Thread(mt2, "MyThread #2"); 11 try { 12 thrd.start(); 13 Thread.sleep(1000); 14 thrd.interrupt(); 15 16 thrd2.start(); 17 System.out.println(); 18 Thread.sleep(4000); 19 thrd2.interrupt(); 20 } catch (InterruptedException e) { 21 System.out.println("Main thread Interrupted"); 22 } 23 } 24 } 25 class MyThread implements Runnable { 26 27 @Override 28 public void run() { 29 String thrdName = Thread.currentThread().getName(); 30 System.out.println(thrdName + " starting."); 31 32 try { 33 Thread.sleep(3000); 34 for(int i= 0;i<1000;i++) { 35 if(Thread.interrupted()) {//判断线程是否是中断 36 System.out.println("Thread interrupted while active."); 37 break; 38 } 39 System.out.print("."); 40 for(long x=0;x<1000000;x++) ; 41 } 42 } catch (InterruptedException e) { 43 System.out.println(thrdName + " interrupted."); 44 } 45 System.out.println(thrdName + " exiting."); 46 } 47 48 }