[英]what is the point of rejoining the thread to the main-thread after the thread has been interrupted?
我从Java教程oracle看了下面的代码。 我只是想知道在中断之后将线程重新连接到主线程有什么意义?
if(((System.currentTimeMillis() - startTime) > patience) && t.isAlive()){
threadMessage("tired of waiting");
t.interrupt();
t.join();
}
我从if语句中删除了t.join()
,并且看起来一切都一样。 那么,为什么编写代码的方式呢?
public class SimpleThreads {
static void threadMessage(String message){
String threadName = Thread.currentThread().getName();
System.out.format("%s: %s%n", threadName, message);
}
private static class MessageLoop implements Runnable {
@Override
public void run (){
String[] importantInfo = { "dog", "cat", "mice"};
try {
for(int i = 0; i < importantInfo.length; i++){
Thread.sleep(4000);
threadMessage(importantInfo[i]);
}
} catch (InterruptedException e){
threadMessage("i wasn't done!");
}
}
}
public static void main(String[] args) throws InterruptedException {
long patience = 10000;
threadMessage("starting MessageLoop 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");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.