java多線程示例 模擬生產者消費者
public class ProducerConsumer {public static void main(String[] args) { SyncStack ss=new SyncStack(); Producer pro=new Producer(ss); Consumer con=new Consumer(ss); new Thread(pro).start(); new Thread(pro).start(); new Thread(con).start(); }
} class Product{ int id; public Product(int id){ this.id=id; } public String toString(){//重寫toString 方法,給pro加上編號,以便調試 return "product "+id; } } class SyncStack{//棧,先進后出 Product[] proArr=new Product[6];//定義容器只能裝6件產品 int index=0; public synchronized void push(Product pro){ while(index==proArr.length){//當容器裝滿了產品,暫停生產 try{ this.wait(); }catch(InterruptedException e){ e.printStackTrace(); } } this.notifyAll();//喚醒消費者消費 proArr[index]=pro; index++;
} public synchronized Product pop(){//同步,確保不被打斷 while(index==0){//當容器里沒有產品可消費,暫停消費 try{ this.wait(); }catch(InterruptedException e){ e.printStackTrace(); } } this.notifyAll();//喚醒生產者生產 index--; return proArr[index]; }
} class Producer implements Runnable{ SyncStack ss=null; public Producer(SyncStack ss){ this.ss=ss; } public void run() { for(int i=0;i<20;i++){ Product pro=new Product(i); ss.push(pro); System.out.println("生產了:"+pro); try{//方便觀察結果,沒有實際意義 Thread.sleep((int)(Math.random()200)); }catch(InterruptedException e){ e.printStackTrace(); } } } } class Consumer implements Runnable{ SyncStack ss=null; public Consumer(SyncStack ss){ this.ss=ss; } public void run(){ for(int i=0;i<20;i++){ Product pro=ss.pop(); System.out.println("消費了:"+pro); try{//方便觀察結果,沒有實際意義 Thread.sleep((int)(Math.random()1000)); }catch(InterruptedException e){ e.printStackTrace(); } } } } </pre>