有人可以解释这段代码中的竞争条件在哪里。我的讲师设置了它,我还不完全理解如何发现它们,或者说为什么会出现给出的结果。
public class SlowRace {
public static void main(String args []) throws Exception {
MyThread.count = 0 ;
MyThread thread1 = new MyThread() ;
thread1.name = "A" ;
MyThread thread2 = new MyThread() ;
thread2.name = "B" ;
thread1.start() ;
thread2.start() ;
thread2.join() ;
thread1.join() ;
System.out.println("MyThread.count = " + MyThread.count) ;
}
}
class MyThread extends Thread {
volatile static int count ;
String name ;
public void run() {
for(int i = 0 ; i < 10 ; i++) {
delay() ;
int x = count ;
System.out.println("Thread " + name + " read " + x) ;
delay() ;
count = x + 1;
System.out.println("Thread " + name + " wrote " + (x + 1)) ;
}
}
static void delay() {
int delay = (int) (1000000000 * Math.random()) ;
for(int i = 0 ; i < delay ; i++) {}
}
}
返回的结果:
Thread A read 0
Thread A wrote 1
Thread B read 0
Thread A read 1
Thread B wrote 1
Thread A wrote 2
Thread B read 2
Thread A read 2
Thread B wrote 3
Thread A wrote 3
Thread B read 3
Thread A read 3
Thread B wrote 4
Thread A wrote 4
Thread B read 4
Thread A read 4
Thread B wrote 5
Thread A wrote 5
Thread B read 5
Thread A read 5
Thread B wrote 6
Thread A wrote 6
Thread B read 6
Thread A read 6
Thread B wrote 7
Thread A wrote 7
Thread B read 7
Thread A read 7
Thread B wrote 8
Thread A wrote 8
Thread B read 8
Thread A read 8
Thread B wrote 9
Thread A wrote 9
Thread B read 9
Thread A read 9
Thread B wrote 10
Thread A wrote 10
Thread B read 10
Thread B wrote 11
MyThread.count = 11