我不太明白为什么我会为此代码获取此输出:
public class Example {
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[] = {
"Line 1",
"Line 2",
"Line 3",
"Line 4"
};
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) {
;
}
}
}
public static void main(String args[]) throws InterruptedException {
threadMessage("Starting MessageLoop thread");
Thread t = new Thread(new MessageLoop());
t.start();
threadMessage("Waiting for MessageLoop thread to finish");
while (t.isAlive()) {
threadMessage("Still waiting...");
// Wait maximum of 1 second
// for MessageLoop thread
// to finish.
t.join(1000);
}
threadMessage("Finally!");
}
}
输出:
main: Starting MessageLoop thread main: Waiting for MessageLoop thread to finish main: Still waiting... main: Still waiting... main: Still waiting... main: Still waiting... main: Still waiting... Thread-0: Line 1 main: Still waiting... main: Still waiting... main: Still waiting... main: Still waiting... Thread-0: Line 2 main: Still waiting... main: Still waiting... main: Still waiting... Thread-0: Line 3 main: Still waiting... main: Still waiting... main: Still waiting... main: Still waiting... Thread-0: Line 4 main: Finally!
如果我在循环中写这个语句,Thread main继续执行它。在线程t完成之后,不应该认为线程主应该继续执行吗?
t.join(1000);
然而,bucle继续执行。据我所知,这两行属于主线 - while(t.isAlive()) - threadMessage(“还在等待......”)
我正在尝试理解这个链接的一个例子:
先谢谢你的帮助!!!
答案 0 :(得分:2)
查看join()
方法的文档here。这就是说:
此线程最多等待毫秒毫秒。
您将1000传递给join()
,这意味着,无论thread t
是否完成,主线程最多等待1秒,然后继续。线程t
的休眠超时为4秒,因此,主线程将始终在t
之前完成(在加入超时后)。
如果你想让主线程永远等待,你需要使用join()
(即没有任何参数)。
答案 1 :(得分:1)
while (t.isAlive()) {
threadMessage("Still waiting...");
// Wait maximum of 1 second
// for MessageLoop thread
// to finish.
t.join(1000);
}
t.join(1000)
表示线程t
等待1000毫秒。 t
在打印所有行之前不会死亡。该场景每秒t.join(1000)
超时,t仍然存活(因为每次打印一行时,它会休眠4秒)。 join(1000)
timedout和t.isAlive()
为真,因此您的主线程会打印出Still waiting
..一旦线程t
完成其工作,t.isAlive()
将为false它会打破while循环,然后打印Finally