【发布时间】:2012-12-13 01:15:01
【问题描述】:
我从一个学生那里得到了这个代码,由于涉及x++ 和x-- 的竞争条件,它不能正常工作。他在run() 方法中添加了synchronized 以试图摆脱这个错误,但显然这只排除了线程在same 对象上输入run()(这在第一个从来不是问题place) 但不会阻止独立对象同时更新同一个静态变量x。
public class DataRace implements Runnable {
static volatile int x;
public synchronized void run() {
for (int i = 0; i < 10000; i++) {
x++;
x--;
}
}
public static void main(String[] args) throws Exception {
Thread [] threads = new Thread[100];
for (int i = 0; i < threads.length; i++)
threads[i] = new Thread(new DataRace());
for (int i = 0; i < threads.length; i++)
threads[i].start();
for (int i = 0; i < threads.length; i++)
threads[i].join();
System.out.println(x); // x not always 0!
}
}
由于我们无法在x 上同步(因为它是原始的),我能想到的最佳解决方案是创建一个新的静态对象,如static String lock = "";,并将x++ 和x-- 包含在@987654332 中@块,锁定lock。但这似乎真的很尴尬。有没有更好的办法?
【问题讨论】:
-
您需要同时或分别同步
x++和x--这两个操作吗?顺便说一句,使用锁来解决这个问题似乎并不尴尬(至少对我来说不是)。 -
用
AtomicInteger替换int或同步DataRace.class -
..或者你可以使用“类对象”。即使用 DataRace.class 作为监视器
标签: java multithreading race-condition