自己实现阻塞有界队列

2018-04-28  本文已影响0人  wuyuan0127

import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;/** * 有界队列 (FIFO) * @author wuy * * @param*/

public class ArrayQueue {

Object[] objs;

//实例化 锁

private Lock lock = new ReentrantLock();

//入队 condition

Condition addCondition = lock.newCondition();

//出对 condition

Condition takeCondition = lock.newCondition();

//入队角标

private int addIndex;

//出队角标

private int removeIndex;

//队列长度

private int queueSize;

public ArrayQueue(int size){

objs = new Object[size];

}

final int inc(int i) {

        return (++i == objs.length) ? 0 : i;

    }

/**

* 往队列里面添加 元素

* @param e

*/

public void add(E e){

lock.lock();

while (queueSize == objs.length) {

try {

addCondition.await();

} catch (InterruptedException e1) {

e1.printStackTrace();

}

}

objs[addIndex] = e;

addIndex = inc(addIndex);

++queueSize;

takeCondition.signal();

lock.unlock();

}

/**

* 获取最早添加的元素

*/

@SuppressWarnings("unchecked")

public E take(){

lock.lock();

try {

while(queueSize == 0){

try {

takeCondition.await();

} catch (InterruptedException e1) {

e1.printStackTrace();

}

}

E e = (E)objs[removeIndex];

objs[removeIndex] = null;

removeIndex = inc(removeIndex);

--queueSize;

addCondition.signal();

return e;

}finally{

lock.unlock();

}

}

}

上一篇下一篇

猜你喜欢

热点阅读