描述
簡單的一個例子:
如果你是造東西的廠商,你製造的東西需要有人來買對吧。
會有顧客(一般顧客)直接去廠子裏去拿麼?
你會直接把東西寄給顧客麼?(直銷除外)
很少會有這樣的情況。
所以我們需要商場。
生產者消費者模式差不多就是這個樣子吧。。
多個線程代表了多個人,其中有生產者有消費者。如何保證消費者不會給了錢拿不到貨呢?就是先把貨製造出來,存到超市(阻塞隊列)裏,藍後消費者去超市買(隊列彈出),就醬!
Java實現
這個市場裏有一個生產者和三個消費者,賣方市場啦。
一旦生產者喊:“我有商品了!!”
消費者們就會無腦去搶,當然,有人沒搶到。
import java.util.LinkedList;
import java.util.Queue;
public class test {
public static Object signal = new Object();
public static boolean mark = false;
public static Queue<Boolean> q=new LinkedList<Boolean>();
public void buy(String id) throws Exception {
synchronized (signal) {
if (!mark) {
signal.wait();
}
mark = false;
if(!q.isEmpty()){
System.out.println(id+": "+"take");
q.poll();
}
else System.out.println(id+": "+"No good");
signal.notify();
}
}
public void make() throws Exception {
synchronized (signal) {
if (!mark) {
mark = true;
System.out.println("make");
q.add(true);
signal.notify();
}
signal.wait();
}
}
static class Consumer implements Runnable {
test t;
String id;
public Consumer(test t,String id) {
this.t = t;
this.id=id;
}
public void run() {
try {
while (true) {
t.buy(id);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
static class Product implements Runnable {
test t;
public Product(test t) {
this.t = t;
}
public void run() {
try {
while (true) {
t.make();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws Exception {
test t = new test();
Product p = new Product(t);
Consumer c = new Consumer(t,"1");
Consumer c2=new Consumer(t,"2");
Consumer c3=new Consumer(t,"3");
Consumer c4=new Consumer(t,"4");
Thread t0 = new Thread(p);
Thread t1 = new Thread(c);
Thread t2=new Thread(c2);
Thread t3=new Thread(c3);
Thread t4=new Thread(c4);
t0.start();
t1.start();
t2.start();
t3.start();
t4.start();
}
}
輸出
只截取了一部分。。。好像有的消費者會卡在門口來着。。。我再研究一哈。。。
make
4: take
1: No good
make
3: take
2: No good
make
1: take
4: No good
make
2: take
3: No good
make
4: take
1: No good
make
3: take
2: No good
make
1: take
4: No good
make
2: take
3: No good
make
4: take
1: No good