您现在的位置:首页 > >

用Lock Condition自主实现阻塞队列

发布时间:

package thread.lock_condition;

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

public class MyBlocingQueue {
private final List list;
private final int limit;
private final Lock lock = new ReentrantLock();
private final Condition notEmpty = lock.newCondition();//非空
private final Condition notFull = lock.newCondition();//没满
public MyBlocingQueue(int limit){
this.limit = limit;
this.list = new ArrayList();
}

public void put(E e){
try {
lock.lock();
while(list.size() >= limit){
notFull.await();
}
list.add(e);
notEmpty.notifyAll();
} catch (Exception e2) {
// TODO: handle exception
}finally{
lock.unlock();
}
}

public E take(){
try {
lock.lock();
while(list.size() == 0){
notEmpty.await();
}
E e = list.remove(0);
notFull.notifyAll();
return e;
} catch (Exception e2) {
return null;
}finally{
lock.unlock();
}
}


}



热文推荐
猜你喜欢
友情链接: 医学资料大全 农林牧渔 幼儿教育心得 小学教育 中学 高中 职业教育 成人教育 大学资料 求职职场 职场文档 总结汇报