Dee*_*eVu 3 java multithreading race-condition
以下代码应该通过使用常用的synchronized方法来阻止Data Racing.但由于某种原因,输出始终是19915-19980.如果不是数据竞赛,它不应该是20000吗?
public class SyncVarDataRace extends Thread {
private static int common = 0;
public void run(){
synchronized((Integer)common){
int local = common;
local+=1;
common = local;
}
}
public static void main(String[] args) throws InterruptedException {
SyncVarDataRace[] allThreads = new SyncVarDataRace[20000];
for(int i = 0; i < allThreads.length; i++){
allThreads[i] = new SyncVarDataRace();
}
for(SyncVarDataRace d: allThreads){
d.start();
}
for(SyncVarDataRace d: allThreads){
d.join();
}
System.out.println(common);
}
}
Run Code Online (Sandbox Code Playgroud)
您正尝试在每次都是不同对象的自动装箱对象上进行同步.
synchronized((Integer)common){
Run Code Online (Sandbox Code Playgroud)
重点是在每个线程中同步对象.即使你common是一个Integer,只要你将它分配给另一个值,它就会成为一个不同的对象.
您需要锁定常量对象.我建议您定义一个可以同步的本地对象:
private final static Object lock = new Object();
private static int common = 0;
...
synchronized (lock) {
common++;
}
Run Code Online (Sandbox Code Playgroud)
在这种特定情况下可能会更好,您可以考虑使用AtomicInteger.这允许您在没有任何同步的情况下执行以下操作.
private static AtomicInteger common = new AtomicInteger(0);
...
// no need to synchronize since that is handled by the class
common.incrementAndGet();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
977 次 |
| 最近记录: |