圖解java多執行緒設計模式學習第五章Producer-Consumer模式
生產者消費者模式,生產者安全地將資料交給消費者。雖然僅是這樣看似簡單的操作,但當生產者和消費者以不同的執行緒執行時,兩者之間的處理速度差異便會引起問題。例如,消費者想要獲取資料,可資料還沒有生成,或者生產者想要交付資料,而消費者的狀態還無法接收資料等。一般來說,在該模式中,生產者和消費者都有多個,當然生產者和消費者有時也會只有一個。
有3位糕點師製作蛋糕並將其放到桌子上,然後有三個人來吃這些蛋糕。
糕點師(makerThread)製作蛋糕,並將其放到桌子(Table)上。
桌子上最多可放置3個蛋糕
如果桌子上已經放滿三個蛋糕時糕點師還要再放置蛋糕,必須等到桌子上空出位置
客人取桌子上的蛋糕吃
客人按蛋糕被放置到桌子上的順序來取蛋糕
當桌子上1個蛋糕都沒有時,客人若要取蛋糕,必須等到桌子上新放置了蛋糕
package com.producerconsumer;
public class Table {
private final String[] buffer;
/** 下次put的位置 **/
private int tail;
/** 下次take的位置 **/
private int head;
/** buffer中的蛋糕個數 **/
private int count;
public Table( int count){
this.buffer = new String [count];
this.head = 0;
this.tail = 0;
this.count = 0;
}
/**
* 放置蛋糕
* @param cake
* @throws InterruptedException
*/
public synchronized void put(String cake) throws InterruptedException{
System.out.println(Thread.currentThread().getName() + " puts " +cake);
while(count >= buffer.length){
wait();
}
buffer[tail] = cake;
tail = (tail + 1) % buffer.length;
count++;
notifyAll();
}
public synchronized String take() throws InterruptedException{
while(count <= 0){
wait();
}
String cake = buffer[head];
head = (head + 1)% buffer.length;
count --;
notifyAll();
System.out.println(Thread.currentThread().getName() + " takes " + cake);
return cake;
}
}
package com.producerconsumer;
import java.util.Random;
public class MakeeThread extends Thread{
private final Random random;
private final Table table;
private static int id = 0;
public MakeeThread(String name, Table table, long seed){
super(name);
this.table = table;
this.random = new Random();
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
while(true){
Thread.sleep(random.nextInt(1000));
String cake = "[Cake NO." + nextId() + " by " + getName() + " ] " ;
table.put(cake);
}
} catch (Exception e) {
// TODO: handle exception
}
}
private static synchronized int nextId() {
// TODO Auto-generated method stub
return id++;
}
}
package com.producerconsumer;
import java.util.Random;
public class EaterThread extends Thread{
private final Random random;
private final Table table;
public EaterThread(String name, Table table, long seed){
super(name);
this.table = table;
this.random = new Random(seed);
}
@Override
public void run() {
try {
while(true){
String take = table.take();
Thread.sleep(random.nextInt(1000));
}
} catch (Exception e) {
// TODO: handle exception
}
}
}
package com.producerconsumer;
public class Main {
public static void main(String[] args) {
//建立一個能放置是三個蛋糕的桌子
Table table = new Table(3);
new MakeeThread("MakerThread-1", table, 31415).start();
new MakeeThread("MakerThread-2", table, 92653).start();
new MakeeThread("MakerThread-3", table, 58979).start();
new EaterThread("EaterThread-1", table, 32384).start();
new EaterThread("EaterThread-2", table, 62643).start();
new EaterThread("EaterThread-3", table, 38327).start();
}
}