JavaチュートリアルのOracleから以下のコードを見ました。私はちょうどそれが中断された後にメインスレッドにスレッドを再結合する点は何ですか?スレッドが中断された後、スレッドをメインスレッドに再結合する点は何ですか?
if(((System.currentTimeMillis() - startTime) > patience) && t.isAlive()){
threadMessage("tired of waiting");
t.interrupt();
t.join();
}
文と、すべてがまったく同じに働いているように見える場合、私はから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");
}
}