我只需要用java线程做一个竞争条件的例子,我编写了这段代码,但我不确定它是否有竞争条件。
有人可以告诉我下面的代码是否存在竞争条件,以及如何改进它或使其变得简单?
(抱歉英语不好)
public class RaceCondition extends Thread{
static int count=0; //the variable where the race condition need to happen
static int contador1 = 0; //variables to count
static int contador2 = 0;
static Thread t1 = new Thread(new Runnable() {
public void run(){
while(contador1!=20){
count ++;
System.out.print(count + " ");
contador1++;
}
}
});
static Thread t2 = new Thread(new Runnable() {
public void run(){
while(contador2!=20){
int k = 5;
count += 5*k;
System.out.print(count + " ");
contador2 ++;
}
}
});
public static void main(String[] args) {
t1.start();
System.out.println(" ");
t2.start();
}
}
最佳答案
你确实有竞争条件。 ++
或 +=
操作在 Java 中都不是作为原子操作实现的,两个线程在尝试读取和更新时可能会互相干扰计数字段。
此外,无法保证共享变量的更新在线程之间可见,因此一个线程甚至可能看不到另一线程的更新值。
您可以通过将 count 静态变量设置为 AtomicInteger 来解决这两个问题。 。使用getAndIncrement而不是 ++
和 getAndAdd而不是 +=
。
为什么 ++
会这样工作,请参阅 Why ++ is not implemented as an atomic operation in Java .
关于java - 这段代码有竞争条件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34955113/