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();
}
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有