java167-生产者消费者问题
2022/7/6 14:25:25
本文主要是介绍java167-生产者消费者问题,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
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();
}
}
运行结果
这篇关于java167-生产者消费者问题的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-23Springboot应用的多环境打包入门
- 2024-11-23Springboot应用的生产发布入门教程
- 2024-11-23Python编程入门指南
- 2024-11-23Java创业入门:从零开始的编程之旅
- 2024-11-23Java创业入门:新手必读的Java编程与创业指南
- 2024-11-23Java对接阿里云智能语音服务入门详解
- 2024-11-23Java对接阿里云智能语音服务入门教程
- 2024-11-23JAVA对接阿里云智能语音服务入门教程
- 2024-11-23Java副业入门:初学者的简单教程
- 2024-11-23JAVA副业入门:初学者的实战指南