中断操作是一种简便的线程间交互的方式,这种交互方式最适合用来取消或者停止任务。除了中断外,还能利用一个boolean变量来控制是否需要停止并终止该线程。例如:

 1 class Termination{
 2     public static void main(String[] args) throws Exception{
 3         Runner one = new Runner();
 4         Thread countThread = new Thread(one, "countThread");
 5         countThread.start();
 6         //睡眠1秒,main线程对countThread进行中断,使countThread能够感知中断结束
 7         TimeUnit.SECONDS.sleep(1);
 8         countThread.interrupt();
 9         Runner two = new Runner();
10         countThread = new Thread(two, "countThread");
11         countThread.start();
12         //睡眠1秒,main线程对two进行取消,使countThread能够感知on为false而结束
13         TimeUnit.SECONDS.sleep(1);
14         two.cancel();
15     }
16     private static class Runner implements Runnable{
17         private Long count = 0L;
18         private volatile boolean on = true;
19         @Override
20         public void run(){
21             while (on && !Thread.currentThread().isInterrupted()){
22                 count++;
23             }
24             System.out.println("count =  " + count);
25         }
26         public void cancel(){
27             on = false;
28         }
29     }
30 }

 

posted on 2017-11-26 21:41  飞奔的菜鸟  阅读(170)  评论(0编辑  收藏  举报