java中多线程模拟(多生产,多消费,Lock实现同步锁,替代synchronized同步代码块)

import java.util.concurrent.locks.*;
class DuckMsg{
    int size;//烤鸭的大小
    String id;//烤鸭的厂家和标号
    DuckMsg(){
      
    }
    
    DuckMsg(int size, String id){
       this.size=size;
       this.id=id;
    }
    
    public String toString(){
       return id + " 大小为:"  + size;
    }
}
class Duck{
   
    private int count=0;//生产烤鸭的总数
    private int putId=0, takeId=0;//分别表示存入的Id 和 取出烤鸭的Id
    
    Lock lock = new ReentrantLock();
    DuckMsg[] dk = new DuckMsg[100];//烤鸭的容器
    Condition conProduce = lock.newCondition();
    Condition conConsume = lock.newCondition();
    
    public void put(int sz){
        lock.lock();
        try{
            while(count==dk.length)//一直等到烤鸭全部生产完毕之后所有的生产线程都停止....
               conProduce.await();
            dk[putId++]=new DuckMsg(sz, Thread.currentThread().getName()+":"+(putId-1));
            if(putId==dk.length)  putId=0;//啥意思呢?烤鸭的编号就是1到100, 如果过了100,那么再从编号1开始!
            ++count;
            conConsume.signal();
        }catch(InterruptedException e){
        
        }finally{
            lock.unlock();
        }        
    }
    
    public void get(){
       lock.lock();
       try{
           while(count==0)
               conConsume.await();
           System.out.println(dk[takeId++]);
           System.out.println("......." + Thread.currentThread().getName());//打印消费的厂家
           if(takeId==dk.length)  takeId=0;
           --count;
           conProduce.signal();
        }catch(InterruptedException e){
            
        }finally{
            lock.unlock();
        }
    }
}

class Producer implements Runnable{
    Duck duck;
    Producer(Duck duck){
        this.duck=duck;
    }
    public void run(){
       for(int i=1; ; ++i)
        duck.put(i);
    }
}

class Consumer implements Runnable{
    Duck duck;
    Consumer(Duck duck){
        this.duck=duck;
    }
    public void run(){
        while(true)
          duck.get();
    }
}


public class ProduceConsumeDemo{
      
      public static void main(String[] args){
          Duck duck=new Duck();
          Thread t1 = new Thread(new Producer(duck), "生产厂家 1");
          Thread t2 = new Thread(new Producer(duck), "生产厂家 2");
          Thread t3 = new Thread(new Consumer(duck), "消费厂家 1");
          Thread t4 = new Thread(new Consumer(duck), "消费厂家 2");
          
          t1.start();
          t2.start();
          t3.start();
          t4.start();
      }
}

 

    原文作者:小眼儿
    原文地址: https://www.cnblogs.com/hujunzheng/p/3920876.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞