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)
{
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();
}
}