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

歡迎訪問 生活随笔!

生活随笔

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

java

Java精讲:生产者-消费者

發布時間:2025/3/20 java 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java精讲:生产者-消费者 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

原文鏈接

更多教程


本文概要

生產者和消費者問題是線程模型中老生常談的問題,也是面試中經常遇到的問題。光在Java中的實現方式多達數十種,更不用說加上其他語言的實現方式了。那么我們該如何學習呢?

本文會通過精講wait()和notify()方法實現生產者-消費者模型,來學習生產者和消費者問題的原理。

目的是當你理解了最簡單實現原理,再看其他的實現,無非使用了更高級的機制(例如鎖、信號量、管道等等)來照貓畫虎的實現這個原理,萬變不離其宗,它們的原理都是一樣的。

本文也會列出一部分其他的實現方式代碼。千萬不要嘗試去背誦所有實現代碼,只有掌握了實現原理才能遇到問題的時候游刃有余。

精講wait()和notify()方法實現生產者-消費者模型


  • 啥是生產者-消費者模型:
生產者和消費者在同一時間段內共用同一個存儲空間,生產者往存儲空間中添加產品,消費者從存儲空間中取走產品,當存儲空間為空時,消費者阻塞,當存儲空間滿時,生產者阻塞。

現實生活中的例子:12306搶購火車票、淘寶購買商品、倉庫管理等。

  • 分步的實現我們的模型
public class Test1 {private static Integer count = 0; //代表生產的商品數量private static final Integer FULL = 10; //代表商品最多多少個(也就是緩沖區大小)private static final Object LOCK = new Object(); //鎖對象 ----分析1public static void main(String[] args) {for (int i = 0; i < 5; i++) { //創造一堆生產者和消費者模擬真實環境new Thread(new Producer()).start();}for (int i = 0; i < 5; i++) {new Thread(new Consumer()).start();}}static class Producer implements Runnable { //代表生產者@Overridepublic void run() {}}static class Consumer implements Runnable { //代表消費者@Overridepublic void run() {}} }

分析1.在main函數中創建了5個消費者線程任務和5個生產者線程任務,當這10個線程同時運行時,需要保證生產者和消費者所公用的緩沖區是同步被改變的,就是說不同線程訪問緩沖區的數據不能發生錯亂。這里就是用一個鎖來保證緩沖區每次只有一個線程訪問

接下來看下生產者和消費者的實現:

static class Producer implements Runnable {@Overridepublic void run() {for (int i = 0; i < 10; i++) { //一次多生產幾個商品try {Thread.sleep(3000); //模擬真實環境,讓生產的慢一點,間隔3秒} catch (Exception e) {e.printStackTrace();}synchronized (LOCK) { //線程同步 while (count.equals(FULL)) { //當緩沖區滿了 try {LOCK.wait(); //讓線程等待 ----分析1} catch (Exception e) {e.printStackTrace();}}count++; //緩沖區不滿時繼續生產商品,商品加一System.out.println(Thread.currentThread().getName() + "生產者生產,目前總共有" + count);LOCK.notifyAll(); //喚醒等待的消費者}}}}static class Consumer implements Runnable {@Overridepublic void run() {for (int i = 0; i < 10; i++) {try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}synchronized (LOCK) { while (count == 0) { //當沒有商品時,需要等待生產者生產商品try {LOCK.wait(); //----分析 2} catch (Exception e) {}}count--; //商品被消耗,商品減一System.out.println(Thread.currentThread().getName() + "消費者消費,目前總共有" + count);LOCK.notifyAll(); //商品被消耗后,通知等待的生產者}}}}

分析:
1.當緩沖區滿了的時候,需要阻止生產者繼續生產商品
2.當緩沖區為空,沒有商品時,需要阻止消費者繼續消費商品

相信代碼分析和詳細的注釋,你已經能很好的理解這個生產者-消費者模型的原理了。接下來貼出其他的幾種實現代碼。


原文鏈接

更多教程


其他的實現方法代碼

使用鎖實現:

import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock;public class Test1 {private static Integer count = 0;private static final Integer FULL = 10;//創建一個鎖對象private Lock lock = new ReentrantLock();//創建兩個條件變量,一個為緩沖區非滿,一個為緩沖區非空private final Condition notFull = lock.newCondition();private final Condition notEmpty = lock.newCondition();public static void main(String[] args) {Test1 test1 = new Test1();new Thread(test1.new Producer()).start();new Thread(test1.new Consumer()).start();new Thread(test1.new Producer()).start();new Thread(test1.new Consumer()).start();new Thread(test1.new Producer()).start();new Thread(test1.new Consumer()).start();new Thread(test1.new Producer()).start();new Thread(test1.new Consumer()).start();}class Producer implements Runnable {@Overridepublic void run() {for (int i = 0; i < 10; i++) {try {Thread.sleep(3000);} catch (Exception e) {e.printStackTrace();}//獲取鎖lock.lock();try {while (count == FULL) {try {notFull.await();} catch (InterruptedException e) {e.printStackTrace();}}count++;System.out.println(Thread.currentThread().getName()+ "生產者生產,目前總共有" + count);//喚醒消費者notEmpty.signal();} finally {//釋放鎖lock.unlock();}}}}class Consumer implements Runnable {@Overridepublic void run() {for (int i = 0; i < 10; i++) {try {Thread.sleep(3000);} catch (InterruptedException e1) {e1.printStackTrace();}lock.lock();try {while (count == 0) {try {notEmpty.await();} catch (Exception e) {e.printStackTrace();}}count--;System.out.println(Thread.currentThread().getName()+ "消費者消費,目前總共有" + count);notFull.signal();} finally {lock.unlock();}}}} }

使用阻塞隊列:
當隊列滿了或空了的時候進行入隊列操作都會被阻塞。

import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue;public class Test1 {private static Integer count = 0;//創建一個阻塞隊列final BlockingQueue blockingQueue = new ArrayBlockingQueue<>(10);public static void main(String[] args) {Test1 test1 = new Test1();new Thread(test1.new Producer()).start();new Thread(test1.new Consumer()).start();new Thread(test1.new Producer()).start();new Thread(test1.new Consumer()).start();new Thread(test1.new Producer()).start();new Thread(test1.new Consumer()).start();new Thread(test1.new Producer()).start();new Thread(test1.new Consumer()).start();}class Producer implements Runnable {@Overridepublic void run() {for (int i = 0; i < 10; i++) {try {Thread.sleep(3000);} catch (Exception e) {e.printStackTrace();}try {blockingQueue.put(1);count++;System.out.println(Thread.currentThread().getName()+ "生產者生產,目前總共有" + count);} catch (InterruptedException e) {e.printStackTrace();}}}}class Consumer implements Runnable {@Overridepublic void run() {for (int i = 0; i < 10; i++) {try {Thread.sleep(3000);} catch (InterruptedException e1) {e1.printStackTrace();}try {blockingQueue.take();count--;System.out.println(Thread.currentThread().getName()+ "消費者消費,目前總共有" + count);} catch (InterruptedException e) {e.printStackTrace();}}}} }

原文鏈接

更多教程


總結

以上是生活随笔為你收集整理的Java精讲:生产者-消费者的全部內容,希望文章能夠幫你解決所遇到的問題。

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