java实现生产者-消费者
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就不行啊?去掉任意一个或全去掉就行啊,
谢谢啦。