原文鏈接
更多教程
本文概要
生產者和消費者問題是線程模型中老生常談的問題,也是面試中經常遇到的問題。光在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(); //鎖對象 ----分析1
public 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 { //代表生產者
@Override
public void run() {
}
}
static class Consumer implements Runnable { //代表消費者
@Override
public void run() {
}
}
}
分析1.在main函數中創建了5個消費者線程任務和5個生產者線程任務,當這10個線程同時運行時,需要保證生產者和消費者所公用的緩衝區是同步被改變的,就是說不同線程訪問緩衝區的數據不能發生錯亂。這裏就是用一個鎖來保證緩衝區每次只有一個線程訪問
接下來看下生產者和消費者的實現:
static class Producer implements Runnable {
@Override
public 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 {
@Override
public 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 {
@Override
public 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 {
@Override
public 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 {
@Override
public 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 {
@Override
public 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();
}
}
}
}
}