当i ++被同时执行的线程破坏时,如何建模一种情况? [英] How to model a situation, when i++ is corrupted by simultaneously executing threads?
问题描述
如果int递增/递减操作不是Java 6中的原子操作,也就是说,据说它们是分几个步骤执行的(读取值,递增,写入等),我希望看到一段代码演示多个线程如何以一种可以完全破坏它的方式影响单个int变量.
If int incrementing/decrementing operations are not atomic in Java 6, that is, they are said to be performed in several steps (read the value, increment, write etc), I would like to see a piece of code that will demonstrate how multiple threads can affect a single int variable in a way that will corrupt it entirely.
例如,基本步骤包括但不包括所有这些步骤: i ++〜=将我存入寄存器;增量i(inc asm操作);将我写回内存;
For example, elementary steps include, but not cover all, these: i++ ~= put i to the register; increment i (inc asm operation); write i back to memory;
如果在此过程中有两个或多个线程交织,则可能意味着对i ++的两次后续调用之后的值将仅增加一次.
if two or more threads interleave during the process, that would probably mean that the value after two consequent calls to i++ will be incremented only once.
您能在Java中演示一段在多线程环境中对这种情况进行建模的代码吗?
Can you demonstrate a piece of code in java that models this situation in multithreading environment?
推荐答案
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);
}
}
}
在我的计算机上运行该程序会给出
Running this program on my machine gives
Houston, we have a synchronization problem: counter should be 200000, but it is 198459
这篇关于当i ++被同时执行的线程破坏时,如何建模一种情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!