package thread;
public class ThreadInterruptTest {
/** * @param args */ public static void main(String[] args) { Thread target = new countThead(); target.start();
try { Thread.sleep(10100); } catch (InterruptedException e) { e.printStackTrace(); } target.interrupt(); }
}
class countThead extends Thread { public void run() { int i = 0; while (!isInterrupted()) { System.out.println("running... " + i);
try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.println("Interrupted... ");
// sleep时,被中断,会自动清除当前进程的中断状态,所以isInterrupted()是false。 System.out.println("isInterrupted()... " + isInterrupted());
// 这时,要么进行处理,比如跳出while循环,要么重置中断状态。 Thread.currentThread().interrupt(); }
i++; // 一般代码时被中断,isInterrupted()是true System.out.println("isInterrupted()... " + isInterrupted()); } System.out.println("exit... "); } }
如果上面的代码注释掉Thread.currentThread().interrupt();这行, 那么,假如正在sleep时,被中断了,sleep方法抛出InterruptedException异常, 被抓住,可是没有处理,结果就是循环还继续执行~~~~
有了这句,就没问题了,如下面是某次的运行输出: running... 0 isInterrupted()... false running... 1 isInterrupted()... false running... 2 isInterrupted()... false running... 3 isInterrupted()... false running... 4 isInterrupted()... false running... 5 isInterrupted()... false running... 6 isInterrupted()... false running... 7 isInterrupted()... false running... 8 isInterrupted()... false running... 9 isInterrupted()... false running... 10 Interrupted... isInterrupted()... false isInterrupted()... true exit...
|