package com.dq;
import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class BlockingQueueDemo<E>
{
int size; // 队列最大容量
ReentrantLock lock = new ReentrantLock();
LinkedList<E> list = new LinkedList<>();
// 队列满时的等待条件
Condition conFull = lock.newCondition();
// 队列空时的等待条件
Condition conEmpty = lock.newCondition();
public BlockingQueueDemo(int size)
{
this.size = size;
}
// 入列操作
public void enQueue(E e) throws Exception
{
lock.lock();
try
{
while(list.size() == size)
{
// 这里一定要放在while循环里,因为线程被唤醒后还是要判断是否队列已满
System.out.println("队列满了,别往里进了--------------------------------");
conFull.await();
}
list.add(e);
System.out.println("入列了,元素为:" + e);
conEmpty.signal();
}
finally
{
lock.unlock();
}
}
// 出列操作
public E deQueue() throws Exception
{
E e;
lock.lock();
try
{
while(list.size() == 0)
{
System.out.println("队列是空的,谁出去啊----------------------------------");
conEmpty.await();
}
e = list.removeFirst();
System.out.println("出列了,元素为:" + e);
conFull.signal();
return e;
}
finally
{
lock.unlock();
}
}
public static void main(String[] args)
{
BlockingQueueDemo<Integer> queue = new BlockingQueueDemo<>(20);
new Thread(new Runnable() {
@Override
public void run()
{
for(int index = 0; index < 100; index++)
{
try
{
queue.enQueue(index);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run()
{
for(int index = 0; index < 100; index++)
{
try
{
queue.deQueue();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}).start();
}
}
用Condition实现阻塞队列
最新推荐文章于 2024-07-28 14:57:22 发布