标签:blog io ar java for sp div on 2014
public class Concurrence {
public static void main(String[] args) {
WareHouse wareHouse = new WareHouse();
Producer producer = new Producer(wareHouse);
Consumer consumer = new Consumer(wareHouse);
new Thread(producer).start();
new Thread(consumer).start();
}
}
class WareHouse {
private static final int STORE_SIZE = 10;
private String[] storeProducts = new String[STORE_SIZE];
private int index = 0;
public void pushProduct(String product) {
synchronized (this) {
while (index == STORE_SIZE) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
storeProducts[index++] = product;
this.notify();
System.out.println("生产了: " + product + " , 目前仓库里共: " + index
+ " 个货物");
}
}
public synchronized String getProduct() {
synchronized (this) {
while (index == 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
String product = storeProducts[index - 1];
index--;
System.out.println("消费了: " + product + ", 目前仓库里共: " + index
+ " 个货物");
this.notify();
return product;
}
}
}
class Producer implements Runnable {
WareHouse wareHouse;
public Producer(WareHouse wh) {
this.wareHouse = wh;
}
@Override
public void run() {
for (int i = 0; i < 40; i++) {
String product = "product" + i;
this.wareHouse.pushProduct(product);
}
}
}
class Consumer implements Runnable {
WareHouse wareHouse;
public Consumer(WareHouse wh) {
this.wareHouse = wh;
}
@Override
public void run() {
for (int i = 0; i < 40; i++) {
this.wareHouse.getProduct();
}
}
}
标签:blog io ar java for sp div on 2014
原文地址:http://blog.csdn.net/wzy_1988/article/details/40788067