手写一个阻塞队列

152 阅读1分钟
import java.util.LinkedList;
import java.util.List;

public class MyBlockQueue {
    int capacity;
    List<String> list;
    public static final String PRODUCT = "product";
    public MyBlockQueue(int capacity) {
        this.capacity = capacity;
        list = new LinkedList<>();
    }

    public synchronized void put() {
        while (list.size() >= capacity){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        list.add(PRODUCT);
        this.notifyAll();
    }
    public synchronized void take(){
        while (list.size() == 0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        list.remove(0);
        this.notifyAll();
    }
}