基于线程池的事件通知的生产者与消费者
/**
* 基于线程池的事件通知的生产者与消费者
* @Author: mihuajun 【kobe96688@126.com】
* @Date: 12/9/2018 10:22 AM
*/
public class ThreadPoolProducerConsumerDemo {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(2);
LinkedList<Integer> queue = new LinkedList<>();
executorService.execute(() -> {
for (int i = 0; i < 100; i++) {
synchronized (queue) {
if (queue.size() == 5) {
try {
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(50L);
} catch (InterruptedException e) {
e.printStackTrace();
}
queue.add(i);
System.out.println("add:"+i);
queue.notify();
}
}
});
executorService.execute(() -> {
while (true){
synchronized (queue){
if (queue.size() == 0){
try {
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(50L);
} catch (InterruptedException e) {
e.printStackTrace();
}
Integer item = queue.pop();
System.out.println("remove:"+item);
queue.notify();
}
}
});
}
}
要点:
- 带删除的集合应该用LinkedList之类的存储结构
- 线程应该由线程池管理线程应该由线程池管理
- 线程的nofity(),wait()需要一个公共对象的锁持有
synchronized (queue)
- 线程的notify()可以直接唤醒阻塞的线程
- 线程的wait()可以当前线程等待的同时,释放所持有对象的锁
- 除非调用wait(),
queue
对象在synchronized
代码块执行完才会释放锁