java实现有界队列

package com.cyq;

import java.util.LinkedList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 有界队列的基本实现
 */
public class MyQueue {

    private LinkedList list = new LinkedList<>();

    private AtomicInteger count = new AtomicInteger(0);

    private final int minSize = 0;

    private int maxSize;

    private final Object lock = new Object();

    public MyQueue(int size) {
        this.maxSize = size;
    }

    public void put(Object obj) {
        synchronized (lock) {
            while (count.get() == this.maxSize) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            list.add(obj);
            count.incrementAndGet();
            System.out.println("元素加入:" + obj);

            lock.notify();
        }
    }

    public Object take() {
        Object obj = null;
        synchronized (lock) {
            while (count.get() == this.minSize) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            obj = list.removeFirst();
            count.decrementAndGet();
            System.out.println("元素拿出:" + obj);

            lock.notify();
        }
        return obj;
    }

    public static void main(String[] args) {
        final MyQueue mq = new MyQueue(4);
        System.out.println("初始化四个元素");
        mq.put("aa");
        mq.put("bb");
        mq.put("cc");
        mq.put("dd");
        System.out.println();

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("小明开始放元素了");
                mq.put("ee");
                mq.put("ff");
            }
        });
        t1.start();

        System.out.println();
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("小王开始拿元素了");
                Object o1 = mq.take();
                Object o2 = mq.take();
            }
        });


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

        t2.start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println();
        System.out.println("队列中的元素:");
        for (Object obj : mq.list) {
            System.out.println(obj);
        }
    }

}
 
  

                            
                        
                    
                    
                    

你可能感兴趣的:(java基础)