1. 多線程例子如下:
package com.jzm.multithreading;public class AlwaysEven {private int i=0;public void next(){ i++; i++;}public int getValue(){ return i;}public static void main(String[] args) {final AlwaysEven ae = new AlwaysEven(); new Thread("Watcher"){ public void run() {while(true) {int val = ae.getValue();if(val % 2 != 0) { System.out.println(val); System.exit(0); } }}//end run}.start();while(true)ae.next();}}
結果:列印出一個奇數!!原因是沒有鎖定同步。
2. 下面引入同步機制。
package com.jzm.multithreading;public class AlwaysEven {private int i=0;public synchronized void next(){ i++; i++;}public synchronized int getValue(){ return i;}public static void main(String[] args) {final AlwaysEven ae = new AlwaysEven(); new Thread("Watcher"){ public void run() {while(true) {int val = ae.getValue();if(val % 2 != 0) { System.out.println(val); System.exit(0); } }}//end run}.start();while(true)ae.next();}}
3. 總結: Synchronized中間內嵌了訊號量,從而實現了資源同步。