CreateComponentCore
输出
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'。之后我开始了Thread-0或MessageLoop线程。
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
但是在开始/打印Thread-0消息之前,它打印'main'线程消息'main:等待MessageLoop线程完成',并且在此之后执行Thread-0。为什么?
答案 0 :(得分:1)
这种行为是正常的,必须预料到,尽管你无论如何都不能指望它。
您似乎期望main
线程等待以便第二个线程正在运行。但是,这与您的代码不同。 启动第二个线程的重点是并发执行,这意味着您不能仅因为代码中的语句是顺序的而依赖于执行序列。
如果您希望主线程为wait
以执行其他线程,则需要同步它们。 然而,这违背了在你的情况下启动第二个线程的目的。 如果你想让主线程等待第二个线程,那么你可以在不启动的情况下调用该方法第二个主题。
谷歌搜索&#34; java并发&#34;其中包括this one。该文档解释了很多这些概念。
答案 1 :(得分:-1)
因为在线程上调用start()
不会使线程立即有效执行
这是多线程工作的方式。
来自Thread.start()
文档:
使该线程开始执行; Java虚拟机调用 这个线程的run方法。
结果是两个线程同时运行:当前 thread(从调用start方法返回)和另一个 thread(执行其run方法)。
main
线程当前在您调用t.start();
时执行
线程将一次被JVM暂停,但是你不能掌握。
在您的具体情况下,您将获得可重现的行为
在t.start();
之后,您的执行速度非常快:
threadMessage("Waiting for MessageLoop thread to finish");
它永远不会让主线程暂停并且新线程有效运行。
在t.start();
之后添加一些语句,这些语句需要花费更多时间在主线程中执行或在其上调用sleep()
,您应该会看到不同的行为。