public class BlockingQueueApp {
static class BlockingQueue<T>{
private Queue<T> queue=new LinkedList<>();
private int capacity;
private Lock lock=new ReentrantLock();
private Condition notFull=lock.newCondition();
private Condition notEmpty=lock.newCondition();
public BlockingQueue(int capacity){
this.capacity=capacity;
}
public void put(T element) throws InterruptedException{
lock.lock();
try{
while(queue.size()==capacity){
System.out.println("队列满了");
notFull.await();
}
queue.add(element);
System.out.println("新增"+element);
notEmpty.signal();
}finally {
lock.unlock();
}
}
public T take()throws InterruptedException{
lock.lock();
try {
while(queue.isEmpty()){
System.out.println("队列已空,不能再取");
notEmpty.await();
}
T item=queue.remove();
System.out.println("取出了"+item);
notFull.signal();
return item;
}finally {
lock.unlock();
}
}
}
public static void main(String[] args) throws InterruptedException{
final BlockingQueue<Integer>blockingQueue=new BlockingQueue<>(10);
final Random random=new Random();
Thread thread1=new Thread(new Runnable() {
@Override
public void run() {
while (true){
try {
blockingQueue.put(random.nextInt(10));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Thread thread2=new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
while (true){
try {
while (true){
blockingQueue.take();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thread1.start();
thread2.start();
}
}
解析:
- 这里用了Lock lock=new ReentrantLock() 来同步代码