我在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");
}
}