ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

如何中止Java中的线程

2020-09-24 19:01:22  阅读:277  来源: 互联网

标签:Java Thread thread 中止 -- interrupt 线程 active


如何中止一个运行中的线程

  • 通过Thread.interrupt()
  • 通过线程间的共享标记变量

Java作为第一款官方声明支持多线程的编程语言,其早期提供的一些Api并不是特别的完善,所以可以看到Thread类中的一些早期方法都已经被标记上过时了,例如stop、resume,suspend,destory方法都被标记上过时的标签。那为了弥补这些缺失的功能,后续的Java提供了interrupt这样的方法。

通过interrupt()来中止一个线程

stop方法会立即中止线程的运行并抛出异常,同时释放所有的锁,这可能产生数据安全问题(https://docs.oracle.com/javase/8/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html)。interrupt方法的实现方式更类似于给线程发送了一个信号(简单的理解为给线程设置了一个属性来标记是否应当停止当前线程),线程接收到信号之后具体如何处理,是中止线程还是正常运行取决于运行的线程的具体逻辑。

一个线程中止的最佳实践:

public class StandardInterrupt extends Thread{
    public static void main(String[] args) throws InterruptedException {
        StandardInterrupt standardInterrupt = new StandardInterrupt();
        System.out.println("main thread --> start running");
        standardInterrupt.start();
        Thread.sleep(3000);
        System.out.println("main thread --> aiting for signal");
        standardInterrupt.interrupt();
        Thread.sleep(3000);
        System.out.println("main thread --> stop application");
    }

    public void run(){
        while(!Thread.currentThread().isInterrupted()){
            System.out.println("active thread --> i am working");
            try {
                Thread.sleep(1000);
            }catch (InterruptedException e){
                System.out.println("active thread --> detective interrupt");
                System.out.println("active thread --> check the signal: " +Thread.currentThread().isInterrupted());
                Thread.currentThread().interrupt();
            }
        }
        System.out.println("active thread --> finish my working");
    }
}

//输出
main thread --> start running
active thread --> i am working
active thread --> i am working
active thread --> i am working
main thread --> aiting for signal
active thread --> detective interrupt
active thread --> check the signal: false
active thread --> finish my working
main thread --> stop application

standardInterrupt.interrupt(); 告知active thread应该停止运行了。但是

标签:Java,Thread,thread,中止,--,interrupt,线程,active
来源: https://www.cnblogs.com/Pikzas/p/13725821.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有