生產者——消費者 blockingqueue實現
阿新 • • 發佈:2018-11-11
package Interview; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; class 生產者 implements Runnable{ BlockingQueue<String>queue; public 生產者(BlockingQueue<String> queue){ this.queue=queue; } public void run() { try{ String temp="生產執行緒:"+Thread.currentThread().getName(); System.out.println("生產:"+Thread.currentThread().getName()); queue.put(temp); }catch(InterruptedException e){ e.printStackTrace(); } } } class 消費者 implements Runnable{ BlockingQueue<String>queue; public 消費者(BlockingQueue<String>queue){ this.queue=queue; } @Override public void run() { try { String temp=queue.take(); System.out.println(temp); } catch (InterruptedException e) { // TODO: handle exception e.printStackTrace(); } } } public class 生產者_消費者 { public static void main(String[] args) { // TODO Auto-generated method stub BlockingQueue<String>queue=new LinkedBlockingQueue<String>(2); 生產者 producer=new 生產者(queue); 消費者 customer=new 消費者(queue); for(int i=0;i<5;i++){ new Thread(producer,"producer"+(i+1)).start(); new Thread(customer,"customer"+(i+1)).start(); } } }