代码如下:
public class SynchronizedExample {
/**
* 生产仓库
* @author fancy
*
*/
private static class Factory {
//最大库存量
public static final int MAX_SIZE = 100;
//当前存储数量
public int currentNum;
public Factory() {}
public Factory(int currentNum) {
this.currentNum = currentNum;
}
/**
* 生产指定数量的产品
*/
public synchronized void produce(int needNum) {
while (needNum + currentNum > MAX_SIZE) {
System.out.println("最多只能生产 " + (MAX_SIZE - currentNum) + " , 无法满足需求的数量 " + needNum);
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//满足条件后生产之并更新当前库存
currentNum += needNum;
System.out.println("已经生产了 " + needNum + " , 当前的库存数量为 " + currentNum);
//唤醒在此对象上监听器上等待的所有线程
notifyAll();
}
/**
* 消费者库存
*/
public synchronized void consume(int needNum) {
//需求量大于当前库存
while (needNum > currentNum) {
System.out.println("当前可消费库存只有 " + currentNum + " , 无法满足需求 " + needNum);
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
currentNum -= needNum;
System.out.println("已经消费了 " + needNum + " , 当前的库存数量为 " + currentNum);
notifyAll();
}
}
/**
* 生产者
*/
private static class Productor extends Thread {
private int needNum;
private Factory mFactory;
public Productor(int needNum, Factory mFactory) {
this.needNum = needNum;
this.mFactory = mFactory;
}
@Override
public void run() {
mFactory.produce(needNum);
}
}
/**
* 消费者
*/
private static class Customer extends Thread {
private int needNum;
private Factory mFactory;
public Customer(int needNum, Factory mFactory) {
this.needNum = needNum;
this.mFactory = mFactory;
}
@Override
public void run() {
mFactory.consume(needNum);
}
}
public static void main(String[] args) {
Factory mFactory = new Factory(100);
Customer mCustomer = new Customer(30, mFactory);
Customer mCustomer2 = new Customer(50, mFactory);
Productor mProductor = new Productor(170, mFactory);
mCustomer.start();
mCustomer2.start();
mProductor.start();
}
}