曾经搞了半天, 生产者和消费者模式 加强版(多人生产 多人消费 )..
以前的代码格式就不再吐槽了(以后努力改进)
//输出结果是一个无限循环
import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * 多个生产者&多个消费者模式 * 多个生产者不断生产,多个消费者不停的消费 */ public class LockConditionDemo1 { public static void main(String[] args) { Resource2 r = new Resource2(); Producer2 p = new Producer2(r); Consumer2 c = new Consumer2(r); new Thread(p,"生产者0").start(); new Thread(p,"生产者1").start(); new Thread(p,"生产者2").start(); new Thread(p,"生产者3").start(); new Thread(c,"消费者4").start(); new Thread(c,"消费者5").start(); new Thread(c,"消费者6").start(); new Thread(c,"消费者7").start(); } } //创建数据源 class Resource2{ private String name; private int num=1; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getNum() { return num; } Lock lock = new ReentrantLock(); //创建 Condition con_pro = lock.newCondition(); Condition con_con = lock.newCondition(); Condition c= lock.newCondition(); //创建标记 boolean flag = false;//true 有,fasle没有 int[] arr= new int[5]; int start,end,count; //生产者不断的生产 public void produce() throws InterruptedException{ Thread.sleep(300); lock.lock(); try{ while(count==arr.length){//此处要用while进行判断,不然会概率出现错误 //con_pro.await(); c.await(); } //arr[start] = x; if (++start == arr.length) start = 0; //this.setName("烤鸭"+num); this.setName("烤鸭"); //System.out.println(Thread.currentThread().getName()+"---生产者生产了:"+this.getName()); System.out.println(Thread.currentThread().getName()+"-生产者生产了:"+(count+1)); num++; ++count; //flag = true; //con_con.signalAll(); c.signalAll(); }finally{ lock.unlock(); } } //消费中不断的消费 public void consume() throws InterruptedException{ Thread.sleep(300); lock.lock(); try{ while(count == 0){ //con_con.await(); c.await(); } if (++end == arr.length) end = 0; //this.setName("烤鸭"+num);//不能有//不然num会增加了一个.因为生产完num++了 //System.out.println(Thread.currentThread().getName()+"===========消费者消费了:"+this.getName()); System.out.println(Thread.currentThread().getName()+"====消费者消费了:"+count); //num++;//不能增加 --count; //flag = false; //con_pro.signalAll(); c.signalAll(); }finally{ lock.unlock(); } } } //生产者类 class Producer2 implements Runnable{ Resource2 r; Producer2(Resource2 r){ this.r=r; } @Override public void run() { while(true){//此处要用while进行判断,不然会概率出现错误 try { r.produce(); } catch (InterruptedException e) { e.printStackTrace(); } } } } //消费者类 class Consumer2 implements Runnable{ Resource2 r; Consumer2(Resource2 r){ this.r=r; } @Override public void run() { while(true){ try { r.consume(); } catch (InterruptedException e) { e.printStackTrace(); } } } }
//===============结果==================
生产者0-生产者生产了:1
生产者2-生产者生产了:2
生产者3-生产者生产了:3
消费者6====消费者消费了:3
消费者7====消费者消费了:2
生产者1-生产者生产了:2
消费者4====消费者消费了:2
消费者5====消费者消费了:1
生产者0-生产者生产了:1
消费者6====消费者消费了:1
生产者3-生产者生产了:1
生产者2-生产者生产了:2
消费者7====消费者消费了:2
生产者1-生产者生产了:2
消费者5====消费者消费了:2
消费者4====消费者消费了:1
生产者0-生产者生产了:1
消费者6====消费者消费了:1
生产者3-生产者生产了:1
生产者2-生产者生产了:2
时间: 2024-10-14 07:33:13