JAVA实现阻塞队列

废话不多说直接上代码。嘻嘻!

代码实现:

public class BlockQueueTest {

    final LinkedList<Object> items;

    private int capticy;

    public BlockQueueTest(int i) {
        this.capticy =i;
        this.items = new LinkedList<Object>();
    }


    public int getCapticy() {
        return capticy;
    }
    //添加元素
    public synchronized void add(Object o) throws InterruptedException {
       //需要判断队列是否满了。满了就阻塞
        while (isFull()){
            wait();//阻塞生产者
        }
        items.offer(o);
        notifyAll(); //唤醒消费者去删除队列的元素.

    }
    //移出元素(出队)
    public synchronized Object remove() throws InterruptedException {
        //需要判断队列是位空
        //这块推荐使用while 而不用if, 因为多线程下可能会出现虚假唤醒, 当某个消费者线程被唤醒时,它可能并没有发现队列为空,从而导致虚假唤醒问题。
        while (isEmpty()){
            wait();//阻塞消费者
        }

        Object first = items.poll();
        notifyAll(); //唤醒生产者去添加元素
        return first;
    }


    public boolean isFull(){
        return items.size()>=this.capticy;
    }
    public boolean isEmpty(){
        return items.size()==0;
    }

    public static void main(String[] args) throws InterruptedException {
        BlockQueueTest blockQueueTest = new BlockQueueTest(2);
        for (int i = 0; i < 2;i++) {
            new Thread(()->{
                try {
                    Object remove = blockQueueTest.remove();
                    System.out.println(remove);
                } catch (InterruptedException e) {
                }
            }).start();

        }

        Thread.sleep(10000);
        blockQueueTest.add("2");
        System.out.println(blockQueueTest.items.size());
        blockQueueTest.add("2");
        blockQueueTest.add("2");
        blockQueueTest.add("2");
        blockQueueTest.add("2");
        blockQueueTest.add("2");

    }
}

上述代码实现:

需要判断队列是否为空,或者是否占满,然后去阻塞对应的方法。

引入synchronized 关键字,保证同一方法,同一时刻只能被一个线程所调用。

以上就是一个简单的阻塞队列的代码实现,希望能够帮助到你。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值