以下是OCJP考试的代码
class Test implements Runnable{
synchronized void hit(long n) {
for(int i = 1; i < 3; i++)
System.out.print(n + "-" + i + " ");
}
public static void main(String... args) throws Exception{
new Thread(new Test()).start();
new Thread(new Test()).start();
}
@Override
public void run() {
hit(Thread.currentThread().getId());
}
}
答覆: 8-1 7-1 7-2 8-2及 8-1 8-2 7-1
如何预测这一产出?
发布于 2014-01-14 12:19:36
你无法预测。线程并行运行,输出顺序在线程之间实际上是随机的,尽管顺序在每个单独的线程上都是确定性的。
由于每个线程都有自己的Test对象,所以只与自身同步,所以同步的only ()也不做任何事情。
换句话说,8-2将始终遵循8-1。7-2将始终遵循7-1,但所有7s的顺序与所有8s的顺序完全不同。这意味着,给定一组可能的输出,您可以说有些是不可能的,有些是可能的,但是您无法预测实际的输出结果。
你也应该阅读这个问题及其答案,在这个问题上有非常丰富的信息:
How do you think through and predict the output of a threading question like this?
发布于 2014-01-14 12:23:14
您无法预测,但您可以使用某种计数器来自己设置Thread的名称(如果这对您有任何意义)。
Thread myThread = new Test();
myThread.setName(counter++);
https://stackoverflow.com/questions/21113399
复制相似问题