Posted on 2008-04-21 20:50
橡皮人 阅读(160)
评论(0) 编辑 收藏
package com.nicholas.java;
class KitChen {
private static int MAX_BEADER = 200; // 馒头一天最多做200个
private static int MONEY = 2; // 馒头2块钱一个
static boolean isCell = false;// 判断伙计是否交易完成
static boolean isFulfill = false;// 判断顾客是否交易完成
public void makeBread() {
System.out.println("卖馒头咯,今天的馒头数量为:" + KitChen.MAX_BEADER + "\n"
+ "包子的价格为:" + 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("今天剩余馒头个数为:" + getBread() + " 挣得的钱为:" + MONEY);
}
}
class CustomerA extends Thread {
private KitChen k;
private int count;// 买馒头的个数
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();
}
}