固定长度的线程同步的容器

package com.jiahuilin;

import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class MyContainer1 {
    private LinkedList linkedList=new LinkedList<>();
    private final int MAX=10;
    private int count=0;
    private Lock lock=new ReentrantLock();
    private Condition product=lock.newCondition();
    private Condition consumer=lock.newCondition();
    public   void put(T t)  {
        try {
            lock.lock();
            while(linkedList.size()==MAX){
                System.out.println("队列已满");
                try{
                    product.wait();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            System.out.println("放入"+t);
            linkedList.add(t);
            count++;
            consumer.notifyAll();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }

    public  T get()  {
        try{
            lock.lock();
            while(linkedList.size()==0){
                System.out.println("队列已空");
                try{
                    consumer.wait();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            T t =linkedList.remove();
            count--;
            product.notifyAll();
            return  t;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
        return  null;
    }

    public int getCount(){
        return this.count;
    }

    public static void main(String[] args) {
        MyContainer1 myContainer1=new MyContainer1<>();
        for(int i=0;i<40;i++){
            int j=i;
            new Thread(()->{
                myContainer1.put(j);
            }).start();
        }
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for(int i=0;i<30;i++){
            new Thread(()->{
                int j=myContainer1.get();
                System.out.println("取出"+j);
            }).start();
        }
    }
}

你可能感兴趣的:(多线程)