如果 int 递增/递减操作在 Java 6 中不是原子的,也就是说,它们是分几个步骤执行的(读取值、递增、写入等),我希望看到一段代码演示多个线程如何影响单个 int 变量,从而导致其完全损坏。
例如,基本步骤包括但不涵盖所有这些: i++ ~= 将 i 放入寄存器;增加 i(包括 asm 操作);将 i 写回内存;
如果两个或多个线程在该过程中交错,这可能意味着两次后续调用 i++ 后的值将仅增加一次。
您能用 java 演示一段在多线程环境中模拟这种情况的代码吗?
最佳答案
public class Test {
private static int counter;
public static void main(String[] args) throws InterruptedException {
Runnable r = new Runnable() {
public void run() {
for (int i = 0; i < 100000; i++) {
counter++;
}
}
};
Thread t1 = new Thread(r);
Thread t2 = new Thread(r);
t1.start();
t2.start();
t1.join();
t2.join();
if (counter != 200000) {
System.out.println("Houston, we have a synchronization problem: counter should be 200000, but it is " + counter);
}
}
}
在我的机器上运行这个程序会给出
Houston, we have a synchronization problem: counter should be 200000, but it is 198459
关于java - 当 i++ 因同时执行的线程而损坏时,如何对情况进行建模?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7037268/