Java 生产者消费者模式详细分析(3)

最后的执行结果应当生产一个、消费一个,如此不断循环。如下:

Thread-0----生产者------面包1 Thread-1----消费者-------------面包1 Thread-0----生产者------面包2 Thread-1----消费者-------------面包2 Thread-0----生产者------面包3 Thread-1----消费者-------------面包3 Thread-0----生产者------面包4 Thread-1----消费者-------------面包4 Thread-0----生产者------面包5 Thread-1----消费者-------------面包5 Thread-0----生产者------面包6 Thread-1----消费者-------------面包6 4.使用Lock和Condition实现单生产单消费模式

代码如下:

import java.util.concurrent.locks.*; class Bread { public String name; public int count = 1; public boolean flag = false; //为生产者和消费者提供同一个锁对象以及同一个Condition对象 public static Lock lock = new ReentrantLock(); public static Condition condition = lock.newCondition(); } class Producer implements Runnable { private Bread b; Producer(Bread b){ this.b = b; } public void produce(String name){ b.name = name + b.count; b.count++; } public void run(){ while(true){ //使用Bread.lock来锁住资源 Bread.lock.lock(); try{ if(b.flag){ try{Bread.condition.await();}catch(InterruptedException i){} } produce("面包"); System.out.println(Thread.currentThread().getName()+"----生产者------"+b.name); try{Thread.sleep(10);}catch(InterruptedException i){} b.flag = true; Bread.condition.signal(); } finally { Bread.lock.unlock(); } } } } class Consumer implements Runnable { private Bread b; Consumer(Bread b){ this.b = b; } public String consume(){ return b.name; } public void run(){ while(true){ //使用Bread.lock来锁住资源 Bread.lock.lock(); try{ if(!b.flag){ try{Bread.condition.await();}catch(InterruptedException i){} } System.out.println(Thread.currentThread().getName()+"----消费者-------------"+consume()); try{Thread.sleep(10);}catch(InterruptedException i){} b.flag = false; Bread.condition.signal(); } finally { Bread.lock.unlock(); } } } } public class ProduceConsume_1{ public static void main(String[] args) { //1.创建资源对象 Bread b = new Bread(); //2.创建生产者和消费者对象,将同一个面包对象传递给生产者和消费者 Producer pro = new Producer(b); Consumer con = new Consumer(b); //3.创建线程对象 Thread pro_t = new Thread(pro); Thread con_t = new Thread(con); pro_t.start(); con_t.start(); } } 5.多生产多消费模式(单面包)

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/10c59baee0417f5eec6872d76daae485.html