Java生产者消费者例子,大家看还有哪里可以改进? Java多线程 wait和notify运用 synchronized运用
1.模拟商店 (进货/销售)Shop.java
package com.cloud.factory;
import java.util.ArrayList;
import java.util.List;
import com.cloud.pojo.Product;
/**
* 模拟商店 (进货/销售)
*/
public class Shop {
private static int i = 0;
// 产品的容器;达到容器暂停生产,消费到0等待生产
private static List<Product> list;
static {
list = new ArrayList<Product>();
}
/**
* 生产产品
*/
public synchronized void produ() {
if (list.size() >= 5) {
try {
System.out.println(this.getClass()+"--------------生产商品" + i
+ "时,达到了总数暂停生产-------");
this.wait();// 使当前生产产品的线程 进入休眠
} catch (InterruptedException e) {
System.out.println(e.toString());
e = null;
}
} // 生产商品
Product product = new Product();
product.setName("商品" + i+1);
list.add(product);
System.out.println(this.getClass()+"生产了商品---->" + product.getName() + "商品总数" + i+1);
System.out.println(this.getClass()+"容器容量" + list.size());
i++;
super.notify();
}
/**
* 消费产品
* @return
*/
public synchronized void cousu() {
if (list.size() == 0) {// 消费完时,挂起
System.out.println(this.getClass()+"+++++++++++++++++++++++商品消费完了.等待+++++++++++++++=");
try {
this.wait();//使当前消费产品的线程 进入休眠
} catch (InterruptedException e) {
System.out.println(e.toString());
e = null;
}
}
Product product = list.get(0);
list.remove(0);
System.out.println(this.getClass()+"消费者获得了商品-->" + product.getName());
System.out.println(this.getClass()+"容器容量" + list.size());
super.notify();
}
}
2.实体类Product.java
package com.cloud.pojo;
/**
* Product.java
*/
public class Product {
/**产品名称*/
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
3.消费者Cousumer.java
package com.cloud.thread;
import java.util.Random;
import com.cloud.factory.Shop;
/**
* 消费者
*/
public class Cousumer implements Runnable {
private Shop shop;// 要去消费的商店
public Cousumer(Shop shop) {
this.shop = shop;
}
public void run() {
while (true) {
try {
System.out.println(this.getClass()+" 开始消费...");
int couTime = new Random().nextInt(3000);//生成0-3000毫秒的随机数
Thread.sleep(couTime);
shop.cousu();
System.out.println(this.getClass()+" 消费了一件产品。耗时"+couTime+"毫秒。");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
4.生产者Producer.java