當(dāng)前位置:首頁(yè) > IT技術(shù) > 編程語(yǔ)言 > 正文

數(shù)據(jù)結(jié)構(gòu)與算法-阻塞隊(duì)列
2022-03-06 18:08:50


代碼示例
package *;

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

/**
* @program: data-structure
* @description: 阻塞隊(duì)列
* @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;

/**
* 功能描述:
* 〈創(chuàng)建默認(rèn)大小為10的阻塞隊(duì)列〉
*
* @params : []
* @return :
* @author : cwl
* @date : 2019/9/10 11:07
*/
public MyBlockQueue() {
this(10);
}

/**
* 功能描述:
* 〈創(chuàng)建指定大小的阻塞隊(duì)列〉
*
* @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];
}

/**
* 功能描述:
* 〈往阻塞隊(duì)列中添加元素〉
*
* @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("隊(duì)列滿(mǎn)。。。");
full.await();
}
queue[index] = element;
if (++index == size) {
index = 0;
}
currLen++;
empty.signal();
} finally {
lock.unlock();
}
}

/**
* 功能描述:
* 〈從阻塞隊(duì)列中獲取元素〉
*
* @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("隊(duì)列空。。。");
empty.await();
}
Object obj = queue[removeIndex];
if (++removeIndex == size) {
removeIndex = 0;
}
currLen--;
full.signal();
return (T) obj;
} finally {
lock.unlock();
}
}
}



本文摘自 :https://blog.51cto.com/u

開(kāi)通會(huì)員,享受整站包年服務(wù)立即開(kāi)通 >