Java多线程之通过标识关闭线程

 

 1 package org.study2.javabase.ThreadsDemo.status;
 2 
 3 /**
 4  * @Auther:GongXingRui
 5  * @Date:2018/9/19
 6  * @Description:通过标志位停止线程
 7  **/
 8 public class ThreadStop {
 9     public static void main(String args[]) {
10         Study study = new Study();
11         new Thread(study).start();
12         try {
13             Thread.sleep(100);
14         } catch (InterruptedException e) {
15             e.printStackTrace();
16         }
17         // 外部调用方法关闭线程
18         study.stop();
19     }
20 }
21 
22 class Study implements Runnable {
23     // 1、线程类中定义标识
24     private boolean flag = true;
25 
26     @Override
27     public void run() {
28         // 2、线程体中使用标识
29         while (flag) {
30             System.out.println("线程执行中。。。");
31         }
32     }
33 
34     // 对外提供方法改变标识
35     public void stop() {
36         this.flag = false;
37     }
38 }

 

posted @ 2018-09-19 16:55  星瑞  阅读(473)  评论(0编辑  收藏  举报