產品類:
/** * 產品 * * @author jiazhipeng * @version 1.0 * @date 2016-11-29 */ public class Product { private int id; public Product(int id){ this.id = id; } public String toString(){ return "產品" + id; } }
倉庫類:
/** * 倉庫 * * @author jiazhipeng * @version 1.0 * @date 2016-11-29 */ public class Storage { private BlockingQueue<Product> queue = new ArrayBlockingQueue<>(10); public synchronized void put(Product p) throws InterruptedException{ queue.put(p); } public Product take() throws InterruptedException{ return queue.take(); } }
生產者類:
/** * 生產者 * * @author jiazhipeng * @version 1.0 * @date 2016-11-29 */ public class Producter implements Runnable{ // 自己的信號量 private Semaphore semo1; // 別人的信號量 private Semaphore semo2; private String name; private Storage storage; private Test test; public Producter(Storage storage, Test test, String name, Semaphore semo1, Semaphore semo2){ this.storage = storage; this.test = test; this.name = name; this.semo1 = semo1; this.semo2 = semo2; } @Override public void run() { for(; ; ){ try { semo1.acquire(); int i = test.getInt(); Product p = new Product(i); storage.put(p); System.out.println(name + "成功生產:" + p.toString()); semo2.release(); } catch (InterruptedException e) { e.printStackTrace(); break; } } } }
消費者類:
/** * 消費者 * * @author jiazhipeng * @version 1.0 * @date 2016-11-29 */ public class Consumer implements Runnable{ private String name; private Storage storage; public Consumer(Storage storage, String name){ this.storage = storage; this.name = name; } @Override public void run() { for(; ; ){ try { Product p = storage.take(); System.out.println(name + "成功消費:" + p.toString()); } catch (Exception e) { e.printStackTrace(); break; } } } }
測試類:
/** * 測試 * * @author jiazhipeng * @version 1.0 * @date 2016-11-29 */ public class Test { private int i = 1; public static void main(String[] args) { Test test = new Test(); Storage storage = new Storage(); Semaphore semo1 = new Semaphore(1); Semaphore semo2 = new Semaphore(0); Producter pr1 = new Producter(storage, test, "A1", semo1, semo2); Producter pr2 = new Producter(storage, test, "A2", semo2, semo1); Consumer cr1 = new Consumer(storage, "B1"); Consumer cr2 = new Consumer(storage, "B2"); ExecutorService service = Executors.newCachedThreadPool(); service.submit(pr1); service.submit(pr2); service.submit(cr1); service.submit(cr2); } public synchronized int getInt(){ return i++; } }
Java BlockingQueue生產者消費者實例
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.