gpt4 book ai didi

java - 为什么 Thread.interrupt() 会这样?

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:58:57 25 4
gpt4 key购买 nike

这是对 Java 并发教程中代码的修改

package threads;

public class SimpleThreads {
static void threadMessage(String msg) {
String threadName = Thread.currentThread().getName();
System.out.format("%s: %s%n", threadName,msg);
}
private static class MessageLoop implements Runnable{

@Override
public void run() {
// TODO Auto-generated method stub
String[] importantInfo= {"apple","bat","chlorine","dog","egg","fog","gun"};
try {
for(int i=0;i<importantInfo.length;i++) {
Thread.sleep(4000);
threadMessage(importantInfo[i]);
}
}catch(InterruptedException ie) {
threadMessage("i wasn't done");
}
}
}
/**
* @param args
*/
public static void main(String[] args) throws InterruptedException{
// TODO Auto-generated method stub
long patience = 100;
if(args.length > 0)
try {
patience = Long.parseLong(args[0]) * 1000;
}catch(NumberFormatException nfe) {
System.err.println("argument must be a integer");
System.exit(1);
}
threadMessage("starting message loop thread");
long startTime = System.currentTimeMillis();
Thread t = new Thread(new MessageLoop());
t.start();

threadMessage("waiting for messageloop thread to finish");
while(t.isAlive()) {
threadMessage("still waiting...");
//t.join(1000);
if(((System.currentTimeMillis() - startTime) > patience) && t.isAlive()) {
threadMessage("tired of waiting");
t.interrupt();
//t.join();
}
}
threadMessage("finally");
}

}

这是输出

main: starting message loop thread
main: waiting for messageloop thread to finish
main: still waiting...
main: still waiting...
...(repeats about 100 times)
main: still waiting...
main: still waiting...
main: still waiting...
main: still waiting...
main: tired of waiting
main: still waiting...
main: tired of waiting
main: still waiting...
main: tired of waiting
main: still waiting...
main: tired of waiting
main: still waiting...
main: tired of waiting
Thread-0: i wasn't done
main: finally

我预计在第一个(而且应该是唯一的)main: tired of waiting 之后我会看到 Thread-0: i wasn't done 但是 main : tired of waiting 出现了 5 次——这是为什么?

最佳答案

Thread.Interrupt() 只是向目标线程发送一个中断(信号/异常);它不会立即杀死它。

此外,在您发送中断与目标线程接收并处理中断之间可能存在延迟;不保证上下文切换是立即的。

您可以通过执行某种形式的阻塞操作(例如 I/O 或 sleep )或调用 Thread.yield() 来鼓励(但不是强制)JVM 更快地进行上下文切换。

关于java - 为什么 Thread.interrupt() 会这样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1806690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com