Java多线程-生产者与消费者
生活随笔
收集整理的這篇文章主要介紹了
Java多线程-生产者与消费者
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Java多線程生產者與消費者,準確說應該是“生產者-消費者-倉儲”模型,使用了倉儲,使得生產者消費者模型就顯得更有說服力。
對于此模型,應該明確一下幾點:
1、生產者僅僅在倉儲未滿時候生產,倉滿則停止生產。
2、消費者僅僅在倉儲有產品時候才能消費,倉空則等待。
3、當消費者發現倉儲沒產品可消費時候會通知生產者生產。
4、生產者在生產出可消費產品時候,應該通知等待的消費者去消費。
一、倉庫
可以選擇有線程安全的PriorityBlockingQueue也可以使用普通的list,為了更加體現多線程這里使用沒有線程安全的普通list
使用LinkedList是因為刪除時更加方便。
二、生產者
三、消費者
static class CustomerThread implements Runnable {private int count = 0;public CustomerThread(int count) {this.count = count;}@Overridepublic void run() {while(true){synchronized (list) {if(list.size() < count){System.out.println("容器中數量不夠," + list.size());try {list.wait();// 等待} catch (Exception e) {e.printStackTrace();}}for(int i =1;i<=count;i++){String remove = list.remove();System.out.println("消費掉一個產品--"+remove);}list.notify();}}}}四、測試類
public static void main(String[] args) {// 每次生產10個Thread proTh = new Thread(new ProductThread(10));// 每次消費6個Thread cusTh = new Thread(new CustomerThread(6));proTh.start();cusTh.start();}這樣一個簡單的生產者消費者模型就完成了。
總結
以上是生活随笔為你收集整理的Java多线程-生产者与消费者的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 家里装修想用定制地板,柏尔定制地板怎么样
- 下一篇: java美元兑换,(Java实现) 美元