我最近在一次采访中被问到这个问题。
给定以下代码,静态整数 num
的最小和最大可能值是多少?
import java.util.ArrayList;
import java.util.List;
public class ThreadTest {
private static int num = 0;
public static void foo() {
for (int i = 0; i < 5; i++) {
num++;
}
}
public static void main(String[] args) throws Exception{
List<Thread> threads = new ArrayList<Thread>();
for (int i = 0; i < 5; i++) {
Thread thread = new Thread(new Task());
threads.add(thread);
thread.start();
}
for (int i = 0; i < 5; i++) {
threads.get(i).join();
}
// What will be the range of num ???
System.out.println(ThreadTest.num);
}
}
class Task implements Runnable {
@Override
public void run() {
ThreadTest.foo();
}
}
我告诉他们最大值为 25(如果没有竞争条件),最小值为 5(如果每次迭代时所有线程之间都存在竞争条件)。
但面试官说最小值甚至可以低于5。
这怎么可能?
最佳答案
我声称可能的最小值是 2。
关键在于num++
的非原子性,即它是一个读和一个写,中间可能还有其他操作。
调用线程 T1..T5:
- T1 读取 0,T2 读取 0;
- T1写入1次,然后读写3次。
- 然后 T2 写入 1;
- 然后 T1 读取 1;
- 然后 T2-5 完成所有工作
- 最后,T1 写入 2。
(注意:结果 2 不依赖于线程数或迭代次数,前提是每个线程至少有 2 个。)
但诚实的答案是:这真的不重要。存在数据竞争,如 JLS 17.4.5 中所定义。 :
When a program contains two conflicting accesses (§17.4.1 ["Two accesses to (reads of or writes to) the same variable are said to be conflicting if at least one of the accesses is a write."]) that are not ordered by a happens-before relationship, it is said to contain a data race.
(线程中的操作之间不存在发生之前关系)
所以你不能有效地依赖它所做的任何事情。这只是错误的代码。
(此外,我知道这个问题的答案并不是因为调试多线程代码或深入的技术阅读了一些来之不易的战斗:我知道这一点是因为我之前在其他地方读过这个答案。这是一个客厅技巧,仅此而已,并且因此询问最小值并不是一个很好的面试问题)。
关于java - 竞争条件 : Min and Max range of an integer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58154466/