[英]Java Thread interrupt() - how fast is it performed?
Thread
在調用其interrupt()
方法后需要停止/消失多少時間?
考慮以下代碼:
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();
}
分配t.flag = false;
有什么作用嗎? 換句話說,線程可以在中斷之前退出其run()
方法並“正常”終止嗎?
為了共享數據,需要volatile
。 更好的方法是捕獲InterruptedException。
public class MyThread {
public volatile boolean flag = true;
public void run() {
try {
while(flag) {
doSomething();
Thread.sleep(20);
}
} catch (InterruptedException ie) {
...
}
}
}
請再次檢查isInterrupted,並再次拋出它,因為當返回true時,它將消耗該消息。
public class MyThread {
public void run() {
try {
while(!Thread.isInterrupted()) {
doSomething();
Thread.sleep(20);
}
} catch (InterruptedException ie) {
Thread.interrupt();
}
}
}
使該標志不必要。
如果要使用該標志並優雅地完成代碼,則無需使用中斷並捕獲異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.