wait/notify实现简单阻塞队列

package com.netease.music;

import java.util.LinkedList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CustomerBlockingQueue<T> {

    private int max;

    private int count = 0;

    private final Object lock = new Object();

    public CustomerBlockingQueue(int max) {
        this.max = max;
    }

    private LinkedList<T> list = new LinkedList<T>();

    public void put(T t) {
        synchronized (lock) {
            while (count == max) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            list.addLast(t);
            System.out.println("new Obj add -> " + t);
            count++;
            lock.notifyAll();
        }
    }

    public T get() {
        T t;
        synchronized (lock) {
            while (count == 0) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            t = list.getFirst();
            list.removeFirst();
            count--;
            lock.notifyAll();
        }
        return t;
    }

    public static void main(String[] args) {
        final CustomerBlockingQueue<Integer> queue = new CustomerBlockingQueue<Integer>(6);
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i =0; i< 20; i ++) {
            executorService.submit(new Put(i, queue));
        }
        try {
            System.out.println("开始阻塞,已放部分数据");
            Thread.sleep(3000);
            System.out.println("结束阻塞,准备GET");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < 20; i++) {
            executorService.submit(new Runnable() {
                public void run() {
                    System.out.println("get obj -> " + queue.get());
                }
            });
        }
    }


}

class Put implements Runnable {

    int obj;

    CustomerBlockingQueue<Integer> queue;

    public Put(int obj, CustomerBlockingQueue<Integer> queue) {
        this.obj = obj;
        this.queue = queue;
    }

    public void run() {
        queue.put(obj);
    }
}

复制代码

转载于:https://juejin.im/post/5cb1552c5188251b1e7fb84f

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值