wait/notify实现简单阻塞队列

1,179 阅读1分钟
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);
    }
}