我正在学习Thread Java,我在official docs java上学习教程
此示例组合了各种方法:join()
、sleep()
、interrupt()
和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!");
}
}
为什么作者在interrupt()
之后使用join()
?
这样做的目的是什么?因为我试着 comments 它,什么都没有改变.