I'm learning in Thread Java and I follow the tutorial on official docs java
This example combines various methods: join()
, sleep()
, interrupt()
and , start()
public class SimpleThread {
// Display a message, preceded by
// the name of the current thread
static void threadMessage(String message) {
String threadName = Thread.currentThread().getName();
System.out.format("%s: %s%n", threadName, message);
}
private static class MessageLoop implements Runnable {
public void run() {
String importantInfo[] = {
"Mares eat oats",
"Does eat oats",
"Little lambs eat ivy",
"A kid will eat ivy too"
};
try {
for (int i = 0;
i < importantInfo.length;
i++) {
// Pause for 4 seconds
Thread.sleep(4000);
// Print a message
threadMessage(importantInfo[i]);
}
} catch (InterruptedException e) {
threadMessage("I wasn't done!");
}
}
}
public static void main(String[] args) throws InterruptedException {
// Delay, in milliseconds before
// we interrupt MessageLoop
// thread (default 10s).
long patience = 1000 * 10;
threadMessage("Starting MessageLoop thread");
long startTime = System.currentTimeMillis();
Thread t = new Thread(new MessageLoop(), "MessageLoop");
t.start();
threadMessage("Waiting for MessageLoop thread to finish");
while (t.isAlive()) {
threadMessage("Still waiting...");
t.join(16000);
if (((System.currentTimeMillis() - startTime) > patience) && t.isAlive()) {
threadMessage("Tired of waiting!");
t.interrupt();
t.join();
}
}
threadMessage("Finally!");
}
}
Why the author use join()
after interrupt()
?
what is the purpose of this? Because I try to comment it, nothing changes.
Calling interrupt on a thread signals the thread to terminate, but it doesn't force it. So the thread might still be running. Calling join will force the calling thread to wait until the interrupted thread finishes, or itself is interrupted.
In your thread, the bulk of the waiting is caused by Thread.sleep(). When you call interrupt, the current or next sleep call will end with an interrupted exception. That means your working threads that get interrupted will end very quickly. Calling join probably isn't necessary in this case because the threads terminate so quick.