2019-03-08 14:28:39 1392浏览
今天扣丁学堂Java培训老师给大家介绍一下关于Java生产者消费者模式,结合实例形式分析了java生产者消费者模式的相关组成、原理及实现方法,首先java的生产者消费者模式,有三个部分组成,一个是生产者,一个是消费者,一个是缓存,这么做有什么好处呢?下面我们一起来看一下吧。
/** * 我是生产者,负责生产 */ 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(); } } }
/** * *我是缓存,负责产品的存(生产后的放置)取(消费时的获取) */ 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生产"); 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(); } }
【关注微信公众号获取更多学习资料】