Bry*_*ero 0 java static multithreading java-threads
我只需要用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中的原子操作实现的,当两个线程都试图读取和更新计数字段时,它们可能会相互干扰.
此外,无法保证跨线程可以看到对共享变量的更新,因此一个线程甚至可能看不到另一个线程的更新值.
您可以通过将计数静态变量设置为AtomicInteger来解决这两个问题.使用getAndIncrement代替++,而使用getAndAdd代替+=.
为什么这样++工作,请参阅为什么++没有实现为Java中的原子操作.
| 归档时间: | 
 | 
| 查看次数: | 143 次 | 
| 最近记录: |