1. import java.util.concurrent.TimeUnit;
2. public class SafeFail {
3. private volatile static int nextNum = 0;
4. public static void main(String[] args) throws InterruptedException {
5. for (int i = 0; i < 10; i++) {
6. Thread t = new Thread(new Runnable() {
7. public void run() {
8. while (nextNum < 2000) {
9. int t = getNext();
10. System.out.println(t);
11. }
12. }
13. }, "name_" + i);
14. t.start();
15. TimeUnit.NANOSECONDS.sleep(1);
16. }
17. }
18. public static int getNext() {
19. return nextNum++;
20. }
21. }
1. ++ 不是原子操作,执行两项操作。首先取值,然后写一个新值。如果第二个线程在取旧值与写新的值是读取,那么第二个线程就会返回相同的值。这是安全性失败,safety failure.
public class StopThread {
private static boolean stop;
main {
Thread t = new Thread ( new Runnable () {
run () {
int i=0;
while (!stop)
i++;
}
}) ;
t.start();
Thread.sleep(1);
stop = true;
}
}
你可能会期望t线程在一秒后停掉,然而,可能并不会如愿,因为主线程对stop所做的修改,并不能保证对t是可见的。没有同步,代码会被编译为
if (!stop)
while (true)
i ++;
结果是t线程不会停止。这个被称做活性失败。liveness failure。
转自:http://blog.csdn.net/viterming/archive/2010/11/15/6010609.aspx