implement-your-own blocking queue in java

后端 未结 4 1023
日久生厌
日久生厌 2021-02-02 00:01

I know this question has been asked and answered many times before, but I just couldn\'t figure out a trick on the examples found around internet, like this or that one.

4条回答
  •  旧巷少年郎
    2021-02-02 00:26

    I would like to write a simple blocking queue implementation which will help the people to understand this easily. This is for someone who is novice to this.

    class BlockingQueue {
    private List queue = new LinkedList();
    
    private int limit = 10;
    
    public BlockingQueue(int limit){
        this.limit = limit;
    }
    
    public synchronized void enqueue(Object ele) throws InterruptedException {
        while(queue.size() == limit)
            wait();
        if(queue.size() == 0)
            notifyAll();
        // add
        queue.add(ele);
    }
    
    public synchronized Object deque() throws InterruptedException {
        while (queue.size() == 0)
            wait();
        if(queue.size() == limit)
            notifyAll();
        return queue.remove(0);
    }
    

    }


提交回复
热议问题