第 4 节 生产者与消费者
问题的引出
package com.alpha;
class Info {
private String title;
private String content;
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public void setContent(String content) {
this.content = content;
}
public String getContent() {
return content;
}
}
class Productor implements Runnable {
private Info info;
public Productor(Info info) {
this.info = info;
}
@Override
public void run() {
for (int i = 0; i < 100; i ++) {
if (i % 2 == 0) {
this.info.setTitle("mori");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.info.setContent("好学生");
} else {
this.info.setTitle("可爱的萌动物");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.info.setContent("草泥马");
}
}
}
}
class Customer implements Runnable {
private Info info;
public Customer(Info info) {
this.info = info;
}
@Override
public void run() {
for (int i = 0; i < 100; i ++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(this.info.getTitle() + " - " + this.info.getContent());
}
}
}
public class MainClass{ // 主类
public static void main(String[] args) {
Info info = new Info();
new Thread(new Productor(info)).start();
new Thread(new Customer(info)).start();
}
}解决数据错乱问题
解决重复的问题
总结
最后更新于