前几天写的,简单模拟了生产者消费者,不是很完美,大家多提意见
/**
* 生产者和消费者由商店管理
*/
class Shop extends Thread {
int product;
boolean empty = true;
//放入商品
public synchronized void put(int pro) {
while (empty == false) {
try {
wait();
} catch (Exception e) {
}
}
product = pro;
empty = false;
System.out.println("put the: " + product);
notify();
}
//取走商品
public synchronized int get() {
while (empty == true) {
try {
wait();
} catch (Exception e) {
}
}
empty = true;
System.out.println("get the: " + product);
notify();
return product;
}
}
/**
* 生产者
*/
class Producter extends Thread {
int product;
Shop shop;
public Producter(Shop s) {
product = 0;
shop = s;
}
public void run() {
for (int i = 0; i < 10; i++) {
shop.put(i);
}
}
}
/**
* 消费者
*/
class Consumer extends Thread {
int product;
Shop shop;
public Consumer(Shop s) {
product = 0;
shop = s;
}
public void run() {
for (int i = 0; i < 10; i++) {
product = shop.get();
}
}
}
public class ProducerConsuner {
public static void main(String args[]) {
Shop sh = new Shop();
Producter p = new Producter(sh);
Consumer c = new Consumer(sh);
p.start();
c.start();
}
}