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());
}
}
}