zoukankan      html  css  js  c++  java
  • 终止java线程的2种方法

    1、使用一个volatile的共享变量

    2、使用interrupt方法

    import java.util.concurrent.TimeUnit;
    
    /**
     * ThreadTest
     */
    public class ThreadTest implements Runnable {
    
        private volatile boolean stop = false;
    
        @Override
        public void run() {
            while (!stop) {
                System.out.println(Thread.currentThread().getName() + " is running...");
                try {
                    TimeUnit.MILLISECONDS.sleep(1000);
                } catch (InterruptedException e) {
                    System.out.println("wake up from block");
                    stop = true;
                }
            }
            System.out.println(Thread.currentThread().getName() + " is exiting...");
        }
    
        public static void main(String[] args) {
            ThreadTest threadTest = new ThreadTest();
            Thread t1 = new Thread(threadTest);
            t1.start();
            try {
                TimeUnit.MILLISECONDS.sleep(3000);
            } catch (InterruptedException e) {
                //
            }
    
            // 1、使用 volatile共享变量
            threadTest.stop = true;
    
            // 2、使用interrupt方法
            System.out.println("Interrupt thread:" + t1.getName());
            t1.interrupt();
            try {
                TimeUnit.MILLISECONDS.sleep(3000);
            } catch (InterruptedException e) {
                //
            }
            System.out.println("Stopping application...");
        }
    
    }

    2种可能的运行结果:

    Thread-0 is running...
    Thread-0 is running...
    Thread-0 is running...
    Interrupt thread:Thread-0
    Thread-0 is running...
    wake up from block
    Thread-0 is exiting...
    Stopping application...

    Thread-0 is running...
    Thread-0 is running...
    Thread-0 is running...
    Interrupt thread:Thread-0
    Thread-0 is running...
    Thread-0 is exiting...
    Stopping application...
  • 相关阅读:
    自动化部署之jenkins及简介
    gitlab的备份与恢复与迁移
    P2561 [AHOI2002]黑白瓷砖
    P2042 [NOI2005]维护数列
    P2156 [SDOI2009]细胞探索
    P2154 [SDOI2009]虔诚的墓主人
    P2148 [SDOI2009]E&D
    2019.2.26考试T2 矩阵快速幂加速DP
    loj #6485. LJJ 学二项式定理 (模板qwq)
    P3224 [HNOI2012]永无乡
  • 原文地址:https://www.cnblogs.com/frankyou/p/10119932.html
Copyright © 2011-2022 走看看