//仓库类
class CangKu {
private char[] rl = new char[8]; // rl=容量 仓库最大容量为8.
private int wuPin = 0; // 初始化物品为0.
// 生产函数
public synchronized void shengChan(char a) {
while (wuPin == rl.length) { // 当物品数最大的时候
try {
this.wait(); // 线程终止
} catch (Exception e) {
}
}
this.notify();// 叫醒另一个线程,在当前线程处于就绪状态的前提下。
rl[wuPin] = a;// 向仓库中添加物品。
wuPin++;
System.out.println("生产线程正在生产第" + wuPin + "个产品,该产品是:" + a);
}
// 消费函数
public synchronized void xiaoFei() {
char a;
while (wuPin == 0) {// 当物品数为0的时候
try {
this.wait();// 线程终止。
} catch (Exception e) {
}
}
this.notify();
a = rl[wuPin - 1];// 消费物品。
System.out.println("消费线程正在消费第" + wuPin + "个产品,该产品是:" + a);
wuPin--;
}
}
// 生产类
class ShengChan implements Runnable {
private CangKu xc = null;// 初始化仓库类。
public ShengChan(CangKu xc) {
this.xc = xc;
}
public void run() {// 当主函数运行a.start();的时候,就会执行a.run();
char a;
for (int i = 0; i < 26; i++) {
a = (char) ('A' + i);
xc.shengChan(a);
}
}
}
// 消费类
class XiaoFei implements Runnable {
private CangKu xc = null;
public XiaoFei(CangKu xc) {
this.xc = xc;
}
public void run() {
for (int i = 0; i < 26; i++) {
xc.xiaoFei();// 仓库是一个栈,先进后出,后进先出。
}
}
}
// 主类
public class Test {
public static void main(String[] args) {
CangKu ck = new CangKu();// 新建仓库类对象
ShengChan sc = new ShengChan(ck);// 仓库类对象赋给生产类
XiaoFei xf = new XiaoFei(ck);// 仓库类对象赋给消费类
Thread xc1 = new Thread(sc);// 创建生产类对象的线程1
xc1.start();// 线程开始
Thread xc2 = new Thread(xf);// 创建生产类对象的线程2
xc2.start();// 线程开始
}
}