多线程输出不可预期 [英] Multithread output not expected
问题描述
我是Java和多线程概念的新手.这是我的实验代码:
I am new to Java and the concept of multi-threading. Here's my experimental code:
public class Multithread implements Runnable {
Thread t;
public Multithread(int prior, String name) {
this.t = new Thread(this, name);
this.t.setPriority(prior);
this.t.start();
}
public void run() {
for (int i = 1; i <= 5; i++) {
if (this.t.getName().equals("thread1")) {
System.out.println("First Child Thread Loop No " + i);
}
else {
System.out.println("Second Child Thread Loop No " + i);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
public static void main(String[] args) {
new Multithread(10, "thread1");
new Multithread(7, "thread2");
}
}
输出为:
First Child Thread Loop No 1
Second Child Thread Loop No 1
First Child Thread Loop No 2
Second Child Thread Loop No 2
Second Child Thread Loop No 3
First Child Thread Loop No 3
Second Child Thread Loop No 4
First Child Thread Loop No 4
Second Child Thread Loop No 5
First Child Thread Loop No 5
好吧,我希望这样简单:
Well I expected to be a simple as this:
First Child Thread Loop No 1
Second Child Thread Loop No 1
First Child Thread Loop No 2
Second Child Thread Loop No 2
First Child Thread Loop No 3
Second Child Thread Loop No 3
First Child Thread Loop No 4
Second Child Thread Loop No 4
First Child Thread Loop No 5
Second Child Thread Loop No 5
我希望第一个线程总是在第二个线程之前执行. 请解释我的输出.预先感谢.
I expect first thread to get executed always before the second thread. Please explain my output. Thanks in advance.
推荐答案
原因是当线程开始运行时,您无法猜测它们出现的顺序,这是非常基本的线程问题-您可以阅读: http://www.codeproject.com/Articles/616109/Java-Thread-Tutorial 或 http://www.vogella.com/articles/JavaConcurrency/article.html 或任何其他基本的Thread导师. 祝你好运.
The reason for that is when threads start running you cannot guess the order of their appearing, very basic threads issue - you can read: http://www.codeproject.com/Articles/616109/Java-Thread-Tutorial or http://www.vogella.com/articles/JavaConcurrency/article.html or any other basic Thread tutor. Good luck.
这篇关于多线程输出不可预期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!