//可以尝试把下面的关键字synchronized去掉。
public class cubbyhole {
private int contents;
private boolean available = false;
public synchronized int get() {
while (available == false) {
try {
wait();
} catch (interruptedexception e) {
}
}
available = false;
notifyall();
return contents;
}
public synchronized void put(int value) {
while (available == true) {
try {
wait();
} catch (interruptedexception e) {
}
}
contents = value;
available = true;
notifyall();
}
}
public class producer extends thread {
private cubbyhole cubbyhole;
private int number;
public producer(cubbyhole c, int number) {
cubbyhole = c;
this.number = number;
}
public void run() {
for (int i = 0; i < 10; i++) {
cubbyhole.put(i);
system.out.println("producer #" + this.number + " put: " + i);
try {
sleep((int) (math.random() * 100));
} catch (interruptedexception e) {
}
}
}
}
public class consumer extends thread {
private cubbyhole cubbyhole;
private int number;
public consumer(cubbyhole c, int number) {
cubbyhole = c;
this.number = number;
}
public void run() {
int value = 0;
for (int i = 0; i < 10; i++) {
value = cubbyhole.get();
system.out.println("consumer #" + this.number + " got: " + value);
}
}
}
public class producerconsumertest {
public static void main(string[] args) {
cubbyhole c = new cubbyhole();
producer p1 = new producer(c, 1);
consumer c1 = new consumer(c, 1);
p1.start();
c1.start();
}
}
