【Java多线程】queue

队列,从一端进从另一端出
我们用put和take方法可以模拟
put:像队列中放元素,把Object加到BlockingQueue里,如果BlockingQueue没有空间,则调用此方法的线程被阻断
take:从队列中取元素,取走BlockingQueue里排在首位的对象,如果BlockingQueue为空,阻断进入等待状态,直到BlockingQueue
当队列已经满了,put方法需要等待
当队列中元素个数为0,take方法也需要等待


public class MyQueue {
    //1.需要一个承装元素的集合
   private LinkedList<Object> list = new LinkedList<>();

    //2.需要一个计数器
    private AtomicInteger count = new AtomicInteger();

    //3.需要制定上限和下限
    private final int minSize=0;

    private final int maxSize;

    //4.构造方法
    public MyQueue(int size){
        this.maxSize = size;
    }

    //5.初始化一个对象,用于加锁
    private final Object lock = new Object();

    //put(anObject):把Object加到BlockingQueue里,如果BlockingQueue没有空间,则调用此方法的线程被阻断,
    //直到BlockingQueue里有空间再继续
    public void put(Object obj){
        synchronized (lock){
            while (count.get()==this.maxSize){
                try {
                    lock.wait();
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
            //1.加入元素
            list.add(obj);
            //2.计数器累加
            count.incrementAndGet();

            //3.通知另外一个线程(唤醒)
            lock.notify();
            System.out.println("新加的元素为:"+obj);
        }
    }

    //take:取走BlockingQueue里排在首位的对象,如果BlockingQueue为空,阻断进入等待状态,直到BlockingQueue
    //有新的数据被加入
    public Object take(){
        Object ret = null;
        synchronized (lock){
            if (count.get() == this.minSize){
                try {
                    lock.wait();
                }catch (InterruptedException e){
                    e.printStackTrace();
                }

            }
            //1.移除第一个元素
            ret= list.removeFirst();
            //2.计数器减一
            count.decrementAndGet();
            //3.通知另外一个线程(唤醒)
            lock.notify();
        }

        return ret;
    }

    public int getSize(){
        return this.count.get();
    }

    public static void main(String[] args){
       final MyQueue mq= new MyQueue(5);

        mq.put("a");
        mq.put("b");
        mq.put("c");
        mq.put("d");
        mq.put("e");

        System.out.println(mq.getSize());

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                mq.put("f");
                mq.put("g");
            }
        },"t1");

        t1.start();

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                Object o1 = mq.take();
                System.out.println("移除的元素为"+o1);
                Object o2 = mq.take();
                System.out.println("移除的元素为"+o2);
            }
        },"t2");

        try{
            TimeUnit.SECONDS.sleep(2);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        t2.start();
    }
}

结果:

这里写图片描述

猜你喜欢

转载自blog.csdn.net/zjy15203167987/article/details/80400658
今日推荐