日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

Java多线程-生产者与消费者

發布時間:2024/10/8 java 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java多线程-生产者与消费者 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Java多線程生產者與消費者,準確說應該是“生產者-消費者-倉儲”模型,使用了倉儲,使得生產者消費者模型就顯得更有說服力。
對于此模型,應該明確一下幾點:
1、生產者僅僅在倉儲未滿時候生產,倉滿則停止生產。
2、消費者僅僅在倉儲有產品時候才能消費,倉空則等待。
3、當消費者發現倉儲沒產品可消費時候會通知生產者生產。
4、生產者在生產出可消費產品時候,應該通知等待的消費者去消費。

一、倉庫
可以選擇有線程安全的PriorityBlockingQueue也可以使用普通的list,為了更加體現多線程這里使用沒有線程安全的普通list

private static LinkedList<String> list = new LinkedList<String>();

使用LinkedList是因為刪除時更加方便。
二、生產者

/*** 生產者* * @author Administrator* */static class ProductThread implements Runnable {private int count = 0;public ProductThread(int count) {this.count = count;}@Overridepublic void run() {while(true){synchronized (list) {if(list.size()>20){//容量達到20以上,等待消費try {list.wait();} catch (InterruptedException e) {e.printStackTrace();}}for(int i = 1;i<count ;i++){System.out.println("生產了一個產品---"+i);list.add("str"+i);}list.notifyAll();}}}}

三、消費者

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多线程-生产者与消费者的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。