java实现生产者-消费者

1213333 1213333 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
class Message {
private String title;
private String content;
private boolean flag = true;

public synchronized void set(String title, String content) {
if (flag == false) {
try {
super.wait();
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
else{
this.title = title;
this.content = content;}
this.flag = false;
super.notify();
}

public synchronized void get() {
if (flag == true) {
try {
super.wait();
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
else{
System.out.println(this.title + "---->" + this.content);}
this.flag = true;
super.notify();
}
}

class Producer implements Runnable { // 定义生产者
private Message mes = null;

public Producer(Message mes) {
this.mes = mes;
}

public void run() {
for (int i = 0; i < 20; i++) {
if (i % 2 == 0) {
this.mes.set("**", "学习java");
} else {
this.mes.set("**", "学习C++");
}
}
}
}

class Consumer implements Runnable { // 定义消费者
private Message com = null;

public Consumer(Message com) {
this.com = com;
}

public void run() {
for (int i = 0; i < 20; i++) {
this.com.get();
}
}
}

public class ProducerConsumer {
public static void main(String[] args) throws Exception {
Message msg = new Message(); // 定义Message对象,用于保存和取出数据
new Thread(new Producer(msg)).start(); // 启动生产者线程
new Thread(new Consumer(msg)).start(); // 取得消费者线程
}
}
为什么加了这else就不行啊?去掉任意一个或全去掉就行啊,
谢谢啦。
...全文

相关推荐

评论 5
收藏 已收藏
分享
返回顶部
1213333
Java SE 62,620 成员 307,251 内容