標籤:
先不多說,直接上個例子,著名的生產者消費者問題。
1 public class ProducerConsumer { 2 public static void main(String[] args) { 3 SyncStack ss = new SyncStack(); 4 Producer p = new Producer(ss); 5 Consumer c = new Consumer(ss); 6 new Thread(p).start();//生產者線程 7 new Thread(c).start();//消費者線程 8 } 9 }10 /**11 消費的物品---窩頭12 **/13 class WoTou {14 int id; 15 WoTou(int id) {16 this.id = id;17 }18 public String toString() {19 return "WoTou : " + id;20 }21 }22 /**23 消費的空間---堆棧24 **/25 class SyncStack {26 int index = 0;27 WoTou[] arrWT = new WoTou[6];28 29 public synchronized void push(WoTou wt) {30 while(index == arrWT.length) {//是while而不是if的原因,當wait被打斷的時候依舊要檢查下堆棧是否滿了31 try {32 this.wait();33 } catch (InterruptedException e) {34 e.printStackTrace();35 }36 }37 this.notifyAll(); 38 arrWT[index] = wt;39 index ++;40 }41 42 public synchronized WoTou pop() {43 while(index == 0) {44 try {45 this.wait();46 } catch (InterruptedException e) {47 e.printStackTrace();48 }49 }50 this.notifyAll();51 index--;52 return arrWT[index];53 }54 }55 56 /**57 生產者類58 **/59 class Producer implements Runnable {60 SyncStack ss = null;61 Producer(SyncStack ss) {62 this.ss = ss;63 }64 65 public void run() {66 for(int i=0; i<20; i++) {67 WoTou wt = new WoTou(i);68 ss.push(wt);69 System.out.println("生產了:" + wt);70 try {71 Thread.sleep((int)(Math.random() * 200));72 } catch (InterruptedException e) {73 e.printStackTrace();74 } 75 }76 }77 }78 /**79 消費者類80 **/81 class Consumer implements Runnable {82 SyncStack ss = null;83 Consumer(SyncStack ss) {84 this.ss = ss;85 }86 87 public void run() {88 for(int i=0; i<20; i++) {89 WoTou wt = ss.pop();90 System.out.println("消費了: " + wt);91 try {92 Thread.sleep((int)(Math.random() * 1000));93 } catch (InterruptedException e) {94 e.printStackTrace();95 } 96 }97 }98 }
效果
synchronized的引入,學過資料庫系統和作業系統的朋友應該會有所瞭解,對於共用資源,當一個線程佔用的時候不能被其他線程操作,和作業系統的原子操作的原理有些相似。當synchronized之後,就會獲得對象鎖,其他線程就無法獲得對象鎖。
wait的引入:例如上題堆棧中只能放6個窩頭,但是當堆棧中有6個窩頭的時候,生產者獲得對象鎖的時候就不能生產了,因此,生產者就會進入wait池,同時又會釋放對象鎖。
notify的引入:喚醒wait池中的一個線程(ps:只能喚醒別的線程,不能喚醒自己)
notifyall的引入:喚醒wait池中的所有線程
在最後,給大家說下wait和sleep的區別吧,個人理解:
1.wait是Object類中方法,會拋出InteruptException,sleep是Thread類中的方法,wait方法只用在獲得對象所得時候才能用,否則會拋異常;
2.wait方法會釋放對象鎖,但是sleep不會釋放對象鎖;
3.wait後的線程需要其他的線程去喚醒,但是sleep的線程在規定的時間後會自動喚醒。
java中線程同步問題