生產者和消費者:當生產者在生產時,消費者等待。生產者生產完畢,喚醒消費者,消費者消費。消費者消費時,生產者等待,消費者消費完畢,喚醒生產者生產。實現代碼如下:
//生產者和消費者<br />class Info<br />{<br />private String str1="中國";<br />private String str2="武漢";<br />public boolean flag=false;<br />public synchronized void setStr1(String str1){ //set方法<br />this.str1=str1;<br />}<br />public synchronized void setStr2(String str2){ //set方法<br />this.str2 = str2;<br />}<br />public synchronized String getStr1(){ //get方法<br />return this.str1;<br />}<br />public synchronized String getStr2(){ //get方法<br />return this.str2;<br />}<br />//統一的set方法,進行一次設定<br />public synchronized void set(String str1,String str2){<br />if(flag){<br />try{<br />super.wait(); //不可生產,等待<br />}catch(InterruptedException e){<br />e.printStackTrace();<br />}<br />}</p><p>this.setStr1(str1);<br />this.setStr2(str2);<br />System.out.println("設定完成");<br />flag=true; //修改標誌位<br />try{<br />Thread.sleep(300); //在喚醒線程之前先休息300mm<br />}<br />catch(InterruptedException e){<br />e.printStackTrace();<br />}<br />super.notify(); //喚醒線程</p><p>}<br />//統一的get方法,進行一次資源取出<br />public synchronized void get(){<br />if(!flag){<br />try{<br />super.wait();<br />}catch(InterruptedException e){<br />e.printStackTrace();<br />}<br />}</p><p>System.out.println("取出"+this.getStr1()+"----->"+this.getStr2());<br />flag=false; //修改標誌位</p><p>try{<br />Thread.sleep(300); //在喚醒線程之前先休息300mm<br />}<br />catch(InterruptedException e){<br />e.printStackTrace();<br />}</p><p>super.notify();<br />}</p><p>}<br />class Producter implements Runnable<br />{<br />private Info info = null;<br />public Producter(Info info){<br />this.info = info;<br />}<br />private boolean flag2=true;</p><p>public void run(){<br />for(int i=0;i<50;i++){<br />if(flag2){<br />info.set("中國","武漢");<br />flag2=false;<br />}else{<br />info.set("美國","紐約");<br />flag2=true;<br />}</p><p>}</p><p>}</p><p>}<br />class Consumer implements Runnable<br />{<br />private Info info=null;<br />public Consumer(Info info){<br />this.info = info;<br />}<br />public void run(){<br />for(int i=0;i<50;i++){<br />this.info.get();<br />}</p><p>}</p><p>}<br />public class Demo26<br />{<br />public static void main(String args[]){<br />Info info = new Info();<br />Producter p = new Producter(info);<br />Consumer c = new Consumer(info);<br />Thread tp = new Thread(p);<br />Thread tc = new Thread(c);<br />tp.start();<br />tc.start();<br />}</p><p>}
這這裡使用了notify進行喚醒,關於notify的使用,通過查閱API其定義是:“喚醒在此對象監視器上等待的單個線程。如果所有線程都在此對象上等待,則會選擇喚醒其中一個線程。選擇是任意性的,並在對實現做出決定時發生。線程通過調用其中一個 wait 方法,在對象的監視器上等待。 ”結合以上代碼不難理解,notify在Info類內進行的調用,Info產生的對象是所有線程共同監聽的對象。本程式中定義了兩個線程,此兩個線程共同監聽互相喚醒。
生產者和消費的定義不難理解,關鍵問題是對代碼的理解,