Posted on 2008-04-21 20:50
橡皮人 閱讀(163)
評論(0) 編輯 收藏
package com.nicholas.java;
class KitChen {
private static int MAX_BEADER = 200; // 饅頭一天最多做200個(gè)
private static int MONEY = 2; // 饅頭2塊錢一個(gè)
static boolean isCell = false;// 判斷伙計(jì)是否交易完成
static boolean isFulfill = false;// 判斷顧客是否交易完成
public void makeBread() {
System.out.println("賣饅頭咯,今天的饅頭數(shù)量為:" + KitChen.MAX_BEADER + "\n"
+ "包子的價(jià)格為:" + KitChen.MONEY);
}
public synchronized void setBread(int bread) {
while (!KitChen.isFulfill) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (KitChen.isCell) {
this.notify();
}
if (KitChen.MAX_BEADER > 1) {
KitChen.MAX_BEADER -= bread;
MONEY *= bread;
System.out.println("饅頭賣出 " + bread + "\n" + "收入金額為:"
+ KitChen.MONEY);
KitChen.isCell = true;
} else {
System.out.println("不好意思今天的饅頭全部賣光了@");
}
}
public int getBread() { // 剩余的饅頭
return KitChen.MAX_BEADER;
}
public void foot() {
System.out.println("今天剩余饅頭個(gè)數(shù)為:" + getBread() + " 掙得的錢為:" + MONEY);
}
}
class CustomerA extends Thread {
private KitChen k;
private int count;// 買饅頭的個(gè)數(shù)
CustomerA(KitChen k) {
super("豬頭");
this.k = k;
}
public void run() {
System.out.println("<" + Thread.currentThread().getName() + ">"
+ " 我要饅頭");
System.out.println("<老板 >" + Thread.currentThread().getName()
+ " 你要買多少饅頭?");
count = 2;
System.out.println(Thread.currentThread().getName() + " 我要" + count);
KitChen.isFulfill = true;
k.setBread(count);
System.out.println(Thread.currentThread().getName() + "所買饅頭" + count);
}
}
class CustomerB extends Thread {
private KitChen k;
private int count;
CustomerB(KitChen k) {
super("八戒");
this.k = k;
}
public void run() {
System.out.println("<" + Thread.currentThread().getName() + ">"
+ " 我要饅頭");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO 自動生成 catch 塊
e.printStackTrace();
}
System.out.println("<老板 >" + Thread.currentThread().getName()
+ " 你要買多少饅頭?");
count = 4;
System.out.println(Thread.currentThread().getName() + " 我要 " + count);
KitChen.isFulfill = true;
k.setBread(count);
System.out.println(Thread.currentThread().getName() + "所買饅頭" + count);
}
}
public class MyThread {
public static void main(String[] args) {
KitChen kitchen = new KitChen();
kitchen.makeBread();
CustomerA a = new CustomerA(kitchen);
CustomerB b = new CustomerB(kitchen);
a.start();
b.start();
try {
a.join();
} catch (InterruptedException e) {
// TODO 自動生成 catch 塊
e.printStackTrace();
}
try {
b.join();
} catch (InterruptedException e) {
// TODO 自動生成 catch 塊
e.printStackTrace();
}
kitchen.foot();
}
}