我的操作系统中的代码行为遇到了一些困惑.. 现在大家都知道有很多方法可以进行多线程同步,以便无论如何都能获得正确的值!
那么为什么我总是能得到正确的值而不使用同步方式??? !!!
例如查看下面的代码
在常规行为中,下面的程序应该在几秒钟后终止..因为有十个线程访问同一个变量并将其递增一..并且在某些情况下这应该导致计数值不是 100000 .. 这将停止循环.. 我运行这段代码超过 20 分钟.. 它工作得很好..
谁能告诉我发生了什么事:D ??
我的操作系统是 Windows 7,我使用的是 eclipse Kepler .. JVM 是 8 .. 我的 CPU 不是双核 .. 它是常规独奏 .. 2.4 GHZ ...
public class Worker {
int count;
public static void main(String[] args) {
new Worker().run();
}
public void run() {
do {
count = 0;
Thread thread1 = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 10000; i++) {
count++;
}
}
});
Thread thread2 = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 10000; i++) {
count++;
}
}
});
Thread thread3 = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 10000; i++) {
count++;
}
}
});
Thread thread4 = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 10000; i++) {
count++;
}
}
});
Thread thread5 = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 10000; i++) {
count++;
}
}
});
Thread thread6 = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 10000; i++) {
count++;
}
}
});
Thread thread7 = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 10000; i++) {
count++;
}
}
});
Thread thread8 = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 10000; i++) {
count++;
}
}
});
Thread thread9 = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 10000; i++) {
count++;
}
}
});
Thread thread10 = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 10000; i++) {
count++;
}
}
});
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
thread6.start();
thread7.start();
thread8.start();
thread9.start();
thread10.start();
try {
thread1.join();
thread2.join();
thread3.join();
thread4.join();
thread5.join();
thread6.join();
thread7.join();
thread8.join();
thread9.join();
thread10.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Count is: " + count);
} while (count == 100000);
}
}
最佳答案
我怀疑您的 JVM 碰巧生成了 count++
JIT 编译为原子操作的代码...即使它不能保证> 到...并且您的计算机的内存模型并没有那么宽松。
它仍然不安全 - 只是你碰巧在你的架构上逃脱了它。
关于java - 为什么我的代码在不使用同步的情况下可以完美运行..?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26370353/