wait notify 是Object提供的一個機制。
簡單理解就是:他們是配合synchronized來使用的。synchronized獲取鎖,wait釋放并等待鎖,notify通知其他等待鎖的線程,鎖已釋放
BlockingQueue已經(jīng)寫過生產(chǎn)消費的抽象。那么我們直接寫具體的模型實現(xiàn)就可以了。
public class WaitNotifyModel{
private final Object BUFFER_LOCK = new Object();
private final Queue<Task> buffer = new LinkedList<>();
private final int cap;
private final AtomicInteger increTaskNo = new AtomicInteger(0);
public WaitNotifyModel(int cap) {
this.cap = cap;
}
public Runnable newRunnableConsumer() {
return new ConsumerImpl();
}
public Runnable newRunnableProducer() {
return new ProducerImpl();
}
private class ConsumerImpl {
@Override
public void consume() throws InterruptedException {
synchronized (BUFFER_LOCK) {
while (buffer.size() == 0) {
BUFFER_LOCK.wait();
}
Task task = buffer.poll();
assert task != null;
Thread.sleep(500);
System.out.println("consume: " + task.no);
BUFFER_LOCK.notifyAll();
}
}
}
private class ProducerImpl {
@Override
public void produce() throws InterruptedException {
synchronized (BUFFER_LOCK) {
while (buffer.size() == cap) {
BUFFER_LOCK.wait();
}
Task task = new Task(increTaskNo.getAndIncrement());
buffer.offer(task);
System.out.println("produce: " + task.no);
BUFFER_LOCK.notifyAll();
}
}
}
public static void main(String[] args) {
Model model = new WaitNotifyModel(3);
for (int i = 0; i < 5; i++) {
new Thread(model.newRunnableConsumer()).start();
}
for (int i = 0; i < 5; i++) {
new Thread(model.newRunnableProducer()).start();
}
}
}
更好的理解,可以去熟悉synchronized、wait、notifyAll