JAVA实现阻塞队列

Posted zyfzyfzyf

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JAVA实现阻塞队列相关的知识,希望对你有一定的参考价值。

package 多线程并发;

import java.util.Stack;

/**
 * Created by z84102272 on 2018/7/17.
 */
public class BlockQueueImpl {
    private final static Object pushLock = new Object();  //push的锁
    private final static Object popLock = new Object();  //pop的锁
    private Stack<Object> stack;    //存储数据

    public BlockQueueImpl(){
        stack = new Stack<>();
    }

    /**
     * push锁
     */
    private void pushLock(){
        synchronized (pushLock){
            try{
                pushLock.wait();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    /**
     * 释放push锁
     */
    private void pushUnlock(){
        pushLock.notify();
    }

    private void popLock(){
        try {
            popLock.wait();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void popUnlock(){
        popLock.notify();
    }

    public synchronized void push(Object o){
        int MAX_SIZE = 3;
        if (stack.size() >= MAX_SIZE){
            pushLock();
        }
        stack.push(o);
        popUnlock();
    }
    
    public Object pop(){
        if (stack.size()==0){
            popLock();
        }
        Object o  = stack.pop();
        pushUnlock();
        return o;
    }
    

}

  

以上是关于JAVA实现阻塞队列的主要内容,如果未能解决你的问题,请参考以下文章

java中的队列有哪些,有啥区别

Java 阻塞队列

Java 阻塞队列

Java 阻塞队列

Java多线程:阻塞队列与等待唤醒机制初探

Java之阻塞队列深度剖析