package thread.control;
public class ConsumerThread extends Thread {
private Warehouse warehouse;
private int number;
public ConsumerThread(Warehouse obj, int number) {
warehouse = obj;
this.number = number;
}
public void run() {
int value = 0;
for (int i = 0; i < 10; i++) {
value = warehouse.get();
System.out.println("Consumer #" + this.number + " got: " + value);
}
}
}
package thread.control;
public class ProducerConsumerTest {
/**
* @author jzh 2011-12-19
* @param args
*/
public static void main(String[] args) {
Warehouse warehouse = new Warehouse();
ProducerThread producerThread = new ProducerThread(warehouse, 1);
ConsumerThread consumerThread = new ConsumerThread(warehouse, 1);
producerThread.start();
consumerThread.start();
}
}
package thread.control;
public class ProducerThread extends Thread {
private Warehouse warehouse;
private int number;
public ProducerThread(Warehouse obj, int number) {
warehouse = obj;
this.number = number;
}
public void run() {
for (int i = 0; i < 10; i++) {
warehouse.put(i);
System.out.println("Producer #" + this.number + " put: " + i);
try {
sleep(100);
} catch (InterruptedException e) {
}
}
}
}
package thread.control;
public class Warehouse {
private int content;
private boolean available = false;
public synchronized void put(int value) {
while (available == true) {
try {
wait();
} catch (InterruptedException e) {
}
}
content = value;
available = true;
notifyAll();
}
public synchronized int get() {
while (available == false) {
try {
wait();
} catch (InterruptedException e) {
}
}
available = false;
notifyAll();
return content;
}
}