阻塞队列(CountDownLatch代替notify+wait解决wait释放锁,notify不释放锁问题)

import java.util.Date;
import java.util.LinkedList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 1.有界容器
 * 2.队列容器
 * 3.计数
 *
 */
public class MyBlockQueue {
/**
* 队列容器
*/
private final LinkedList<Object> list = new LinkedList<Object>();
private final int begin = 0;
private final int end;

public MyBlockQueue(int length){
this.end = begin + length;
}
/**
* 计数器
*/
private AtomicInteger count = new AtomicInteger();

private final CountDownLatch countDownLatch = new CountDownLatch(1); 

public int getSize(){
return count.get();
}

/**
* 放入元素
*/
public void push(Object obj) throws Exception{
while(count.get() == end){
countDownLatch.await();
}
list.add(obj);
System.out.println("生产元素:"+obj);
count.incrementAndGet();
countDownLatch.countDown();
}

/**
* 消费元素
*/
public Object pop() throws Exception{
while(count.get() == begin){
countDownLatch.await();
}
count.decrementAndGet();
countDownLatch.countDown();
Object obj = list.removeFirst();
System.out.println("消费:"+obj);
return obj;
}

public static void main(String[] args) {




final MyBlockQueue mq = new MyBlockQueue(5);
try {
mq.push("a");
mq.push(5.6);
mq.push(3);
mq.push(new Date());
mq.push(new Double(1));
System.out.println("当前容器的长度:" + mq.getSize());
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
try {
int i = 3;
while(i > 0){
TimeUnit.SECONDS.sleep(4);
mq.push("f"+i);
i--;
}
} catch (Exception e) {
e.printStackTrace();
}

}
},"t1");

t1.start();


Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
try {
TimeUnit.SECONDS.sleep(2);
while(mq.getSize()>0){
mq.pop();
TimeUnit.SECONDS.sleep(2);
}
} catch (Exception e) {
e.printStackTrace();
}
}
},"t2");
t2.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值