zoukankan      html  css  js  c++  java
  • Java 并发编程——优雅的停止线程

     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 }
  • 相关阅读:
    vscode识别预览markdown文件
    工具:静态资源服务器server
    vscode配置easy sass 生成压缩和未压缩的css文件
    cocos Create简单记录
    小程序AR云识别
    小程序被冻结 解冻方法
    vscode设置px转换为rem
    js 打印文本
    .net 启动进程并执行某方法
    c# 创建文件夹、压缩成zip格式并下载
  • 原文地址:https://www.cnblogs.com/siweipancc/p/12486025.html
Copyright © 2011-2022 走看看