public class ProducerAndConsumer {
public static void main(String[] args) {
// 创建商店
final Shop shop = new Shop(10);
// 创建消费者,并为每个消费者启动一个线程
for (int i = 0; i < 5; i++) {
final Consumer c = new Consumer(shop,"消费者"+i);
new Thread(new Runnable() {
public void run() {
// 每个消费者进行50次消费
for (int j = 0; j < 50; j++) {
try {
c.consume();
// 每次消费后随机等待一段时间
Thread.sleep((int) Math.random() * 50);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).start();
}
// 创建生产者,并为每个生产者启动一个线程
for (int i = 0; i < 3; i++) {
final Producer p = new Producer(shop, "生产者"+i);
new Thread(new Runnable() {
public void run() {
// 每个生产者进行50次生产
for (int j = 0; j < 50; j++) {
try {
p.produce();
// 每次生产后随机等待一段时间,
Thread.sleep((int) Math.random() * 50);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).start();
}
}
}
//生产者
class Producer {
private Shop shop;
private String name;
public Producer(Shop shop, String name) {
this.shop = shop;
this.name = name;
System.out.println("创建生产者" + name);
}
// 生产一件商品
public void produce() throws Exception {
/*要注意,为了与Consumer.consume()方法线程同步.
线程锁为shop对象,而不是this,
总结起来:如果希望几个方法(或代码段)线程同步,那么作为线程锁的对象必须为同一个*/
synchronized (shop) {
// 商品数量达到商店最大容量时,释放当前线程的锁,并等待
if (shop.getProductNum() >= shop.getCapacity()) {
System.out.println("仓库已满,等待消费");
shop.wait();
} else {
System.out.println(name + "生产了一件商品");
shop.setProductNum(shop.getProductNum() + 1);
shop.notifyAll();
}
}
}
}
//消费者
class Consumer {
private Shop shop;
private String name;
public Consumer(Shop shop, String name) {
this.shop = shop;
this.name = name;
System.out.println("创建消费者" + name);
}
// 消费一件商品
public void consume() throws Exception {
synchronized (shop) {
if (shop.getProductNum() == 0) {
System.out.println("仓库已空,等待生产");
shop.wait();
} else {
System.out.println(name + "消费一件商品");
shop.setProductNum(shop.getProductNum() - 1);
shop.notifyAll();
}
}
}
}
//商店
class Shop {
// 当前商品数量
private int productNum = 0;
// 最大商品容量
private int capacity;
public Shop(int capacity) {
this.capacity = capacity;
System.out.println("创建商店");
}
public int getProductNum() {
return productNum;
}
public void setProductNum(int productNum) {
this.productNum = productNum;
System.out.println("产品数量:" + productNum);
}
public int getCapacity() {
return capacity;
}
public void setCapacity(int capacity) {
this.capacity = capacity;
}
}
[java线程同步]生产者消费者问题demo
最新推荐文章于 2019-06-06 17:42:01 发布