简体   繁体   English

Java Thread interrupt()-执行速度有多快?

[英]Java Thread interrupt() - how fast is it performed?

How much time does a Thread need to stop/disappear after its interrupt() method has been called? Thread在调用其interrupt()方法后需要停止/消失多少时间?

Consider the following code: 考虑以下代码:

public class MyThread {
    public boolean flag = true;
    public void run() {
        while(flag) {
            doSomething();
            Thread.sleep(20);
        }
    }
}

void foo() {
    MyThread t = new MyThread();
    t.start();
    Thread.sleep(100);
    t.flag = false;
    t.interrupt();
}

Does the assignment t.flag = false; 分配t.flag = false; have any effect? 有什么作用吗? In other words, can a thread exit its run() method and terminate "normally" before it is interrupted? 换句话说,线程可以在中断之前退出其run()方法并“正常”终止吗?

similar question 类似的问题

For sharing data one needs volatile . 为了共享数据,需要volatile Better would be to catch the InterruptedException. 更好的方法是捕获InterruptedException。

public class MyThread {
    public volatile boolean flag = true;
    public void run() {
        try {
            while(flag) {
                doSomething();
                Thread.sleep(20);
            }
        } catch (InterruptedException ie) {
            ...
        }
    }
}

Check agains isInterrupted, anhd throw it again since when it returns true it consumes the message. 请再次检查isInterrupted,并再次抛出它,因为当返回true时,它将消耗该消息。

public class MyThread {
    public void run() {
        try {
            while(!Thread.isInterrupted()) {
                doSomething();
                Thread.sleep(20);
            }
        } catch (InterruptedException ie) {
            Thread.interrupt();
        }
    }
}

Making the flag unecessary. 使该标志不必要。

If you want to use the flag and finish the code gracefully you don't need to use interrupt and catch the Exception. 如果要使用该标志并优雅地完成代码,则无需使用中断并捕获异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM