[英]Why in the following code the output is different when I compile or run it more than once
class Name implements Runnable {
public void run() {
for (int x = 1; x <= 3; x++) {
System.out.println("Run by "
+ Thread.currentThread().getName()
+ ", x is " + x);
}
}
}
public class Threadtest {
public static void main(String [] args) {
// Make one Runnable
Name nr = new Name();
Thread one = new Thread(nr);
Thread two = new Thread(nr);
Thread three = new Thread(nr);
one.setName("A");
two.setName("B");
three.setName("C");
one.start();
two.start();
three.start();
}
}
The answer is different while compiling and running more then one time I don't know why? 答案是不同的,编译和运行超过一次我不知道为什么? any idea. 任何想法。
It should show the same output, but potentially in a different order for each run. 它应该显示相同的输出,但每次运行可能会以不同的顺序显示。
You've got three independent threads: each will show three lines of output, in the obvious order - but there's no guarantee which thread will execute first, etc. In this particular case I don't believe you've got any side effects which would cause truly strange behaviour - just the normal ambiguity of which threads will run when. 你有三个独立的线程:每个都会以明显的顺序显示三行输出 - 但是不能保证哪个线程会先执行,等等。在这种特殊情况下我不相信你有任何副作用会导致真正奇怪的行为 - 只是线程运行时的正常歧义。 Note that on a multicore processor the threads are likely to be running simultaneously - the only synchronization is whatever happens within System.out.println
. 请注意,在多核处理器上,线程可能同时运行 - 唯一的同步是System.out.println
发生的任何事情。
one of them will start running first then the second and lastly the third . 其中一个将首先开始运行,然后是第二个,最后是第三个。 that is depend on thread scheduler on system 这取决于系统上的线程调度程序
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.