外部方式终止线程运行(标志位)

 1 /**
 2  *  线程外部终止(提供标志位用于终止线程)
 3  */
 4 public class ThreadStop implements Runnable{
 5     private boolean flag = true;
 6     private int a = 0;
 7     
 8     @Override
 9     public void run() {
10         while(flag) {
11             System.out.println("正在运行:" + a++);
12         }
13     }
14     
15     public void checkThread() {    //提供给外部的终止方法
16         this.flag = false;
17     }
18     
19     public static void main(String[] args) {
20         ThreadStop threadStop = new ThreadStop();
21         new Thread(threadStop).start();
22         for(int a = 0;a<99;a++) {
23             System.out.println("main"+a);
24             if(a == 50) {    //线程终止条件
25                 System.out.println("main"+a);
26                 threadStop.checkThread();
27                 System.out.println("线程终止");
28             }
29         }
30     }
31 }

 

posted @ 2020-07-07 21:52  梅竹疯狂打豆豆  阅读(233)  评论(0)    收藏  举报