阻塞自定义队列

import java.util.LinkedList;
import java.util.List;

/**
 * Created by Admin on 2018/3/16.
 */
public class BlockingQueue{
    private List queue=new LinkedList();
    private int size=10;
    public BlockingQueue(int size){
        this.size=size;
    }

    public BlockingQueue() {

    }
    public int getSize(){
        return this.queue.size();
    }

    public synchronized  Object poll()throws InterruptedException{
        while (this.queue.size()==0){
            wait();
        }
        if (this.queue.size()==this.size) {
            notifyAll();
        }
        return this.queue.remove(0);
   }
    public synchronized  void push(Object emum) throws InterruptedException{
       while (this.queue.size()==this.size){
           wait();
       }
       if (this.queue.size()==0){
           notifyAll();
       }
       this.queue.add(emum);
    }
}

测试

/**
 * Created by Admin on 2018/3/16.
 */
public class TestBlockingQueue {
    public static void main(String[] args) throws InterruptedException {
        BlockingQueue bq=new BlockingQueue();
        bq.push("b");
        bq.push("ba");
        bq.push("baa");
        bq.push("aaab");
        System.out.println(bq.getSize());
        System.out.println(bq.poll());
        System.out.println(bq.getSize());
        System.out.println(bq.poll());
        System.out.println(bq.getSize());
        System.out.println(bq.poll());
        System.out.println(bq.getSize());
        System.out.println(bq.poll());
        System.out.println(bq.getSize());
        System.out.println(bq.poll());
    }
}

结果

 

posted on 2018-03-16 12:40  Honey_Badger  阅读(245)  评论(0编辑  收藏  举报

导航

github