/**
*
*/
package mythread;
* @author daniel zhou
* 示範生産者、消費者模型
public class WaitAndNotify {
/**
* @param args
*/
public static void main(String[] args) {
// 定義一個儲物罐
Queue q = new Queue();
// 生産者
producer p = new producer(q);
// 消費者
consumer c = new consumer(q);
// 開始生産、消費過程
p.start();
c.start();
System.gc();
}
}
* @author daniel zhou 儲物罐,用作存儲生産者的産品
class Queue {
// 産品編号
int value;
// 有無産品标示
boolean flag = false;
// 生産
public synchronized void put(int i) {
// 為空則放置,并通知消費者去取産品,自己則開始等待
if (!flag ) {
value = i;
flag = true;
// 通知消費者
notify();
}
// 開始等待
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// 消費
public synchronized int get() {
// 有産品則取,并标示已經置空,通知生産者放置,自己開始等待
// 開始等待
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 通知生産者并傳回産品
flag = false;
notify();
return value;
* @author daniel zhou 消費者
class consumer extends Thread {
Queue q;
public consumer(Queue q) {
this.q = q;
// 消費10個産品
public void run() {
//這個while必須要
while(true){
System.out.println("消費者消費了第" + q.get() + "個産品");
* @author daniel zhou 生産者
class producer extends Thread {
public producer(Queue q) {
// 生産10個産品
public void run() {
for (int i = 0; i < 10; i++) {
q.put(i);
System.out.println("生産者放置了第" + i + "個産品");