前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >数据结构与算法-阻塞队列

数据结构与算法-阻塞队列

作者头像
cwl_java
发布2019-10-26 21:15:44
3450
发布2019-10-26 21:15:44
举报
文章被收录于专栏:cwl_Javacwl_Java
代码示例
代码语言:javascript
复制
package *;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @program: data-structure
 * @description: 阻塞队列
 * @author: ChenWenLong
 * @create: 2019-09-10 11:06
 **/
public class MyBlockQueue<T> {

    private int size;
    private Object[] queue;

    private Lock lock = new ReentrantLock();
    private Condition full = lock.newCondition();
    private Condition empty = lock.newCondition();

    private int index;
    private int removeIndex;
    private int currLen;

    /**
     * 功能描述:
     * 〈创建默认大小为10的阻塞队列〉
     *
     * @params : []
     * @return :
     * @author : cwl
     * @date : 2019/9/10 11:07
     */
    public MyBlockQueue() {
        this(10);
    }

    /**
     * 功能描述:
     * 〈创建指定大小的阻塞队列〉
     *
     * @params : [size]
     * @return :
     * @author : cwl
     * @date : 2019/9/10 11:07
     */
    public MyBlockQueue(int size) {
        this.index = 0;
        this.removeIndex = 0;
        this.currLen = 0;
        this.size = size;
        queue = new Object[size];
    }

    /**
     * 功能描述:
     * 〈往阻塞队列中添加元素〉
     *
     * @params : [element]
     * @return : void
     * @author : cwl
     * @date : 2019/9/10 11:10
     */
    public void push(T element) throws InterruptedException {
        lock.lock();
        try {
            while (currLen == size) {
                System.out.println("队列满。。。");
                full.await();
            }
            queue[index] = element;
            if (++index == size) {
                index = 0;
            }
            currLen++;
            empty.signal();
        } finally {
            lock.unlock();
        }
    }

    /**
     * 功能描述:
     * 〈从阻塞队列中获取元素〉
     *
     * @params : []
     * @return : T
     * @author : cwl
     * @date : 2019/9/10 11:10
     */
    public T pop() throws InterruptedException {
        lock.lock();
        try {
            while (currLen == 0) {
                System.out.println("队列空。。。");
                empty.await();
            }
            Object obj = queue[removeIndex];
            if (++removeIndex == size) {
                removeIndex = 0;
            }
            currLen--;
            full.signal();
            return (T) obj;
        } finally {
            lock.unlock();
        }
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-10-18 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 代码示例
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档