# 考察点
- 多线程并发,需要用到synchronized
- 容器满了后,需要进行wait
- notifyAll后,还需要判断容器是否满了或者空了,因为notifyAll是唤醒全部线程,线程开始竞争锁,先拿到锁的运行结束后,容器状态发生变化,后进的线程还是要进行状态的判断
# 代码
```java
package com.suanfa;
import java.util.LinkedList;
import java.util.List;
public class BlockQueue<T> {
LinkedList<T> list = new LinkedList();
private int maxSize = 0;
BlockQueue(int maxSize) {
this.maxSize = maxSize;
}
public synchronized void offer(T t) throws Exception {
while (list.size() == maxSize) {
System.out.println(Thread.currentThread().getName() + ": 满了, 阻塞");
this.wait();
System.out.println(Thread.currentThread().getName() + ": notify");
}
System.out.println(Thread.currentThread().getName() + ": offer");
list.add(t);
this.notifyAll();
}
public synchronized T poll() throws Exception {
while (list.size() == 0) {
System.out.println(Thread.currentThread().getName() + ": 空了, 阻塞");
this.wait();
System.out.println(Thread.currentThread().getName() + ": notify");
}
System.out.println(Thread.currentThread().getName() + ": poll");
T t = list.removeFirst();
this.notifyAll();
return t;
}
public static void main(String[] args) throws Exception {
BlockQueue<String> queue = new BlockQueue(5);
new Thread(() -> {
try {
while (true) {
queue.offer("1");
Thread.sleep(1000);
}
} catch (Exception e) {
e.printStackTrace();
}
}, "t1").start();
new Thread(() -> {
try {
while (true) {
queue.offer("1");
Thread.sleep(1000);
}
} catch (Exception e) {
e.printStackTrace();
}
}, "t2").start();
Thread.sleep(10000);
System.out.println("开始消费");
queue.poll();
}
}
```

基于Wait, NotifyAll的阻塞队列实现