首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java线程中断: interrupt() vs stop()

Java线程中断: interrupt() vs stop()
EN

Stack Overflow用户
提问于 2014-05-27 00:03:19
回答 2查看 1.3K关注 0票数 0

我在Java中使用线程时遇到了一个问题。在Java中,interrupt()和stop()中断线程的首选方法是什么?为什么?

感谢您的回复。

EN

回答 2

Stack Overflow用户

发布于 2014-05-27 00:07:58

从理论上讲,按照您提出问题的方式,线程应该通过同步标志自己理解何时必须终止。

这是通过使用interrupt()方法来完成的,但是您应该理解,只有当您的线程处于等待/睡眠状态(在本例中会抛出异常)时,此方法才能“起作用”,否则您必须在线程的run()方法中检查自己是否线程被中断(使用isInterrupted()方法),并在需要时退出。例如:

代码语言:javascript
复制
public class Test {
    public static void main(String args[]) {
        A a = new A(); //create thread object
        a.start(); //call the run() method in a new/separate thread)
        //do something/wait for the right moment to interrupt the thread
        a.interrupt(); //set a flag indicating you want to interrupt the thread

        //at this point the thread may or may not still running 

    }
}

class A extends Thread {

    @Override
    public void run() { //method executed in a separated thread
        while (!this.isInterrupted()) { //check if someone want to interrupt the thread
            //do something          
        } //at the end of every cycle, check the interrupted flag, if set exit
    }
}
票数 1
EN

Stack Overflow用户

发布于 2014-05-27 00:08:04

Thread.stop()已经在Java8中被弃用了,所以我想说Thread.interrupt()是个不错的选择。在oracles site上有一个冗长的解释。它还提供了一个很好的例子来说明如何使用线程。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23873972

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档