class Order1 {
private static int i = 0;
private int count = i++;// count用来记数, 这里借助一个静态变量来对所创建的对象进行记数
public Order1() {
if(count == 10) {
System.out.println("Out of food, closing");
System.exit(0);
}
}
public String toString() {
return "#" + count;
}
}
class WaitPerson1 extends Thread {
private Restaurant1 res;
private String name;
public WaitPerson1(Restaurant1 rest, String name){
this.res = rest;
this.name = name;
this.start();
}
public void run() {
synchronized(res) {
while(!res.isHaveOrder()) { //如果没有定单就等待
try {
res.wait();
//System.out.println(Thread.currentThread() + " is mantory!");
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
// 这句代码不可以放在while()循环中,否则可以看到有的线程抢到的是null
System.out.println("WaitPerson " + name + " got " + res.consume());
//System.out.println(Thread.currentThread() + " is alive!");
}
}
}
class Chef1 extends Thread {
private Restaurant1 res;
private String name;
public Chef1(Restaurant1 rest, String name) {
this.res = rest;
this.name = name;
this.start();
}
public void run() {
while(true) {
if(!res.isHaveOrder()) {
System.out.println(name + " produces Order " + res.produce());
synchronized(res) {
res.notifyAll();
}
}
}// end while
}
}
public class Restaurant1 {
private Order1 order;
public Order1 produce() {
order = new Order1();
return order;
}
public Order1 consume() {
Order1 temp = order;
order = null;
return temp;
}
public boolean isHaveOrder() {
return order != null;
}
public static void main(String[] args) {
Restaurant1 res = new Restaurant1();
new WaitPerson1(res, "snow");
new WaitPerson1(res, "snee");
new Chef1(res, "tree");
}
}
但是输出结果只有是:
tree produces Order #0
Thread[Thread-1,5,main] is mantory!
WaitPerson snee got #0
Thread[Thread-1,5,main] is alive!
Thread[Thread-0,5,main] is mantory!
tree produces Order #1
Thread[Thread-0,5,main] is mantory!
WaitPerson snow got #1
Thread[Thread-0,5,main] is alive!
tree produces Order #2
为什么到这个地方就停止了???