【发布时间】:2012-11-05 08:06:58
【问题描述】:
假设我们有这种情况:
class Stack{
public void main{
ChildThread1 t1 = new ChildThread1;
ChildThread1 t2 = new ChildThread1;
ChildThread1 t3 = new ChildThread1;
//then we make some ChildThread2 objects and some ChildThread3 objects
ChildThread2 s1 = new ChildThread2;
//...
ChildThread3 v1 = new ChildThread3;
//...
//now we let all threads start in mix order
t1.start();
v1.start();
//...
SOP("All threads are ready");
//then we let them run with join()
t1.join();
t2.join();
t3.join();
s1.join();
//...
v1.join();
//...
每种类型的线程在运行时都会打印出自己独特的语句。
我注意到每次执行程序时,输出总是不同的。例如,来自 ChilThread1 t1 的语句将在输出中间打印而不是开始(因为 t1 首先开始)或者语句“所有线程都准备好”将在线程执行中间弹出(例如:ChilThread2 是'所有线程都准备好了' 运行)
所以我试图找到答案,我找到了这个网站:http://www.avajava.com/tutorials/lessons/how-do-i-use-threads-join-method.html 该网站基本上说当你使用 start() 时没有保证执行顺序
所以我可以假设这种奇怪的打印顺序是因为 start() 不保证执行顺序吗?这个原因是否也适用于“所有线程都准备好”的问题?
【问题讨论】:
-
new ChildThread1应该是new ChildThread1() -
我从来不明白这些问题。如果您想要或期望特定的执行顺序,您为什么要使用线程?如果您不知道线程的用途,为什么还要使用线程?
-
@EJP 每个人都必须在某一时刻学习。为什么要敌对?以一种能教会他新东西的方式回答他的问题。
-
我不是说我想要订购,我只是假设在我阅读那篇文章之前它会按顺序打印。
标签: java multithreading