1 package cn.pancc.purejdk.concurrent;
 2 
 3 import lombok.SneakyThrows;
 4 
 5 import java.util.concurrent.TimeUnit;
 6 
 7 /**
 8  * @author pancc
 9  * @version 1.0
10  */
11 public class StoppableRunner implements Runnable {
12 
13     private volatile boolean sta = true;
14 
15     /**
16      * {@link Thread#currentThread} 返回实际执行 Runnable 的虚拟机线程引用 .
17      * <p>
18      * {@link Thread#isInterrupted()}  每次调用都会清除标志位,设置为 false .
19      * <p>
20      * {@link Thread#interrupt} 会将标志位设置为 true .
21      * <p>
22      * {@link Thread#sleep} 方法同样也会清除标志位,设置为 false,因此当线程中存在 sleep 时,
23      * 单使用 !Thread.currentThread().isInterrupted() 将不可用;
24      * 当 {@link Thread#interrupt} 被调用,尝试 sleep 将会抛出 {@link InterruptedException},
25      * <p>
26      */
27     @SneakyThrows
28     @Override
29     public void run() {
30 
31         int count = 0;
32         while (!Thread.currentThread().isInterrupted() && sta) {
33             System.out.println(count++);
34             TimeUnit.SECONDS.sleep(1);
35 
36         }
37     }
38 
39     public void cancel() {
40         this.sta = false;
41     }
42 
43     public static void main(String[] args) throws InterruptedException {
44         StoppableRunner runner = new StoppableRunner();
45         Thread t = new Thread(runner);
46         t.start();
47         TimeUnit.SECONDS.sleep(4);
48         //  thread.cancel();
49         t.interrupt();
50 
51     }
52 }

 

posted on 2020-03-13 13:46  四维胖次  阅读(245)  评论(0编辑  收藏  举报