2019-03-08 14:28:39 2352瀏覽
今天扣丁學堂Java培訓老師給大家介紹一下關于Java生產(chǎn)者消費者模式,結合實例形式分析了java生產(chǎn)者消費者模式的相關組成、原理及實現(xiàn)方法,首先java的生產(chǎn)者消費者模式,有三個部分組成,一個是生產(chǎn)者,一個是消費者,一個是緩存,這么做有什么好處呢?下面我們一起來看一下吧。
/** * 我是生產(chǎn)者,負責生產(chǎn) */ public class Product implements Runnable { private Queue q; public Product(Queue q) { this.q = q; } @Override public void run() { try { for (int i = 0; i < 3; i++) { q.product("test" + i); } } catch (InterruptedException e) { e.printStackTrace(); } } }
/** *我是消費者,負責消費 */ public class Consumer implements Runnable { private Queue q; public Consumer(Queue q){ this.q = q; } @Override public void run() { try { for(int i=0 ; i < 3 ; i++){ q.consumer(); } } catch (InterruptedException e) { e.printStackTrace(); } } }
/** * *我是緩存,負責產(chǎn)品的存(生產(chǎn)后的放置)取(消費時的獲取) */ public class Queue { private final Object lock = new Object(); private List<String> list = new ArrayList<String>(); public void product(String param) throws InterruptedException { synchronized (lock) { System.out.println("product生產(chǎn)"); list.add(param); lock.notify(); lock.wait(); } } public void consumer() throws InterruptedException { synchronized (lock) { lock.wait(); System.out.println("product消費"); if (list.size() > 0) { list.remove(list.size() - 1); } lock.notify(); } } } public class TestMain { public static void main(String[] args) { Queue q = new Queue(); Product p = new Product(q); Consumer s = new Consumer(q); Thread t1 = new Thread(p); Thread t2 = new Thread(s); t1.start(); t2.start(); } }
【關注微信公眾號獲取更多學習資料】