class Ck {
private char[] r1 = new char[8];
private int wp = 0;
public synchronized void shengchan(char aa) {
while (wp == r1.length) //满了
try {
this.wait();
} catch (Exception e) {
}
this.notify();//叫醒另一个线程,当前线程处于就绪状态
r1[wp] = aa;
++wp;
System.out.println( "生产者正在生产第" + wp + "个产品,该产品为" + aa );
}
public synchronized void xiaofei() {
char aa;
while (wp == 0)
try {
this.wait();
} catch (Exception e) {
}
this.notify();
aa = r1[wp - 1];
System.out.println( "生产者正在消费第" + wp + "个产品,该产品为" + aa );
--wp;
}//代码生产消费问题实现
}
定义生产
//生产
public class Sc implements Runnable {
private Ck xc = null;
public Sc(Ck xc) {
this.xc = xc;
}
public void run() {
char aa;
for (int i = 0; i < 26; i++) {
aa = (char) ('A' + i);
xc.shengchan( aa );
}
}
}
定义消费
//消费
public class Xf implements Runnable {
private Ck xc = null;
public Xf(Ck xc) {
this.xc = xc;
}
public void run() {
char aa;
for (int i = 0; i < 26; i++) {
aa = (char) ('A' + i);
xc.xiaofei();
}
}
}
测试类
//代码生产消费问题实现
public class test119{
public static void main(String[] args){
Ck ck=new Ck();
Sc sc=new Sc( ck );
Xf xf=new Xf(ck);
Thread xc1=new Thread( sc );
xc1.start();
Thread xc2=new Thread( xf );
xc2.start();
}
}
运行结果