【发布时间】:2018-06-29 10:22:12
【问题描述】:
public class SimpleThreads {
// 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++) {
threadMessage(importantInfo[i]);
}
} catch (Exception e) {
threadMessage("I wasn't done!");
}
}
}
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");
}
}
输出
main: Starting MessageLoop thread
main: Waiting for MessageLoop thread to finish
Thread-0: Mares eat oats
Thread-0: Does eat oats
Thread-0: Little lambs eat ivy
Thread-0: A kid will eat ivy too
这里首先主线程打印了消息'main: Starting MessageLoop thread'。之后我启动了 Thread-0 OR MessageLoop 线程。
Thread t = new Thread(new MessageLoop());
t.start();
但在开始/打印 Thread-0 消息之前,它的打印“主”线程消息“main:等待 MessageLoop 线程完成”,并且仅在此之后执行 Thread-0。为什么?
【问题讨论】:
-
Thread t = new Thread(new MessageLoop()); t.start();(在main开始)应该如何在main之前开始?这里有什么令人惊讶的部分? -
main无论如何都会首先被调用 -
因为启动线程不是瞬时的,所以启动线程是有开销的。与线程通过其启动开销并到达其
threadMessage()调用相比,主线程只需更快地 到达第二个threadMessage()调用。这是一个简单的速度问题。这是一个竞态条件,但主线程通常会赢得比赛,因为它在start()和threadMessage()之间没有任何关系。 -
如果没有显式同步,则无法保证这些语句(在不同线程中)的打印顺序。这意味着甚至不确定来自
main线程的waiting消息是否总是首先打印。使用此代码的唯一保证是来自main线程的所有消息都按顺序打印,并且来自Thread-0的所有消息都按顺序打印。 -
感谢大家的宝贵回复。
标签: java multithreading main