很多地方讲多线程时使用了下面UnsafeSequence类的getNext方法,说明如果不同步会得到错误的结果,但我的测试却从未出现过错误,请高手看看是怎么回事,谢谢!
多个线程同时持有对象us,它的getNext方法没有进行同步,按照书上的说法,由于有几个线程会同时拿到value,然后加1,10个线程分别加1后最终应该是一个小于9的值,但测试结果总是9。
[code="java"]
public class Main2 {
public static void main(String[] args) {
UnsafeSequence us = new UnsafeSequence();
for (int i = 0; i < 10; i++) {
Runnable myRunnable = new MyRunnable(us);
new Thread(myRunnable).start();
}
}
}
public class MyRunnable implements Runnable {
private final UnsafeSequence us;
public MyRunnable(UnsafeSequence _us) {
us = _us;
}
@Override
public void run() {
System.out.println("next in " + Thread.currentThread().getName() + ": "
+ +us.getNext());
}
}
public class UnsafeSequence {
public int value = 0;
public int getNext() {
return value++;
}
}[/code]
下面是运行结果:
next in Thread-0: 0
next in Thread-9: 5
next in Thread-7: 4
next in Thread-5: 3
next in Thread-3: 2
next in Thread-1: 1
next in Thread-2: 6
next in Thread-4: 7
next in Thread-6: 8
next in Thread-8: 9