【发布时间】:2016-03-21 22:43:05
【问题描述】:
我不太明白为什么我会得到这段代码的输出:
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: 启动 MessageLoop 线程 main:等待 MessageLoop 线程完成 主:还在等…… 主:还在等…… 主:还在等…… 主:还在等…… 主:还在等…… 线程 0:第 1 行 主:还在等…… 主:还在等…… 主:还在等…… 主:还在等…… 线程 0:第 2 行 主:还在等…… 主:还在等…… 主:还在等…… 线程 0:第 3 行 主:还在等…… 主:还在等…… 主:还在等…… 主:还在等…… 线程 0:第 4 行 主:终于!如果我在循环中编写此语句,Thread main 将继续执行。在线程 t 完成后,线程 main 不应该继续执行吗?
t.join(1000);
但是,bucle 继续执行。据我所知,这两行属于线程主线 - 同时(t.isAlive()) - threadMessage("还在等待...")
我试图理解这个链接的一个例子:
提前感谢您的帮助!!!
【问题讨论】:
-
输出中有什么不明白的地方?你期望什么输出,为什么?
标签: java multithreading join