gpt4 book ai didi

java - 如何预测输出中的线程 ID?

转载 作者:行者123 更新时间:2023-11-29 10:02:11 25 4
gpt4 key购买 nike

以下是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());
}
}

Answer: 8-1 7-1 7-2 8-2 and

8-1 8-2 7-1 7-2

如何预测这个输出?

最佳答案

你无法预测。线程并行运行,输出顺序在线程之间实际上是随机的,尽管顺序在每个单独的线程上是确定的。

hit() 上的同步也没有做任何事情,因为每个线程都有自己的测试对象,所以只与自己同步。

换句话说,8-2 将始终遵循 8-1。 7-2 将始终遵循 7-1,但所有 7 的顺序与所有 8 的顺序完全分开。这意味着给定一组可能的输出,你可以说有些是不可能的,有些是可能的,但你无法预测实际会产生什么输出。

您还应该阅读这个问题及其答案,关于这个主题的信息非常丰富:

How do you think through and predict the output of a threading question like this?

关于java - 如何预测输出中的线程 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21113399/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com