java多线程 生产者_java多线程实现生产者消费者

import java.util.Random;

import java.util.logging.Level;

import java.util.logging.Logger;

public class CustomerProducterThread {

public static void main(String[] args) {

Storage storage = new Storage();

Customer c1 = new Customer(storage);

c1.setName("c1");

Customer c2 = new Customer(storage);

c2.setName("c2");

Customer c3 = new Customer(storage);

c3.setName("c3");

Customer c4 = new Customer(storage);

c4.setName("c4");

Producter p1 = new Producter(storage);

p1.setName("p1");

Producter p2 = new Producter(storage);

p2.setName("p2");

Producter p3 = new Producter(storage);

p3.setName("p3");

Producter p4 = new Producter(storage);

p4.setName("p4");

c1.start();

c2.start();

p1.start();

p2.start();

p3.start();

p4.start();

c3.start();

c4.start();

}

}

class Storage {// 仓库

public static final int[] lock = new int[0];

public static final Integer max = 100;

private Integer sto = 0;

public void put(int i, String name) {// 生产者放

synchronized (lock) {

if ((this.sto + i) > max) {

System.out.println(name + " 仓库已满 ............" + i);

try {

lock.wait();

put(i,name);

// 等 wait 结束后继续调用 put 方法来放置刚才生产的 i 个产品 ,

//即生产的产品放不进时不能丢,等解锁后再放

} catch (InterruptedException ex) {

Logger.getLogger(Storage.class.getName()).log(Level.SEVERE, null, ex);

}

} else {

this.sto = this.sto + i;

System.out.println(name + " 生产了 " + i + " 个产品,现在库存量 " + this.sto);

lock.notifyAll();

}

}

}

public void get(int i, String name) {// 消费者取

synchronized (lock) {

if (this.sto - i 

System.out.println(name + " 仓库余额不足 ............" + i);

try {

lock.wait();

get(i,name);

} catch (InterruptedException ex) {

Logger.getLogger(Storage.class.getName()).log(Level.SEVERE, null, ex);

}

} else {

this.sto = this.sto - i;

System.out.println(name + " 消费了 " + i + " 个产品,现在库存量 " + this.sto);

lock.notifyAll();

}

}

}

}

class Customer extends Thread {// 消费者

public Storage sto;

public Customer(Storage sto) {

this.sto = sto;

}

@Override

public void run() {

while (true) {

sto.get(new Random().nextInt(10) + 1, Thread.currentThread().getName());

}

}

}

class Producter extends Thread {// 生产者

public Storage sto;

public Producter(Storage sto) {

this.sto = sto;

}

@Override

public void run() {

while (true) {

sto.put(new Random().nextInt(10) + 1, Thread.currentThread().getName());

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值