产品类:
public class Info {
private String title = "生产";
private String content = "生产罐头";
private boolean flag = false; // 默认是false
/*
* 1、flag = true,表示可以生产,但是不能取走
*
* 2、flag = false,表示可以取走,但是不能生产
*/
public synchronized void set(String title, String content) {
if (flag == false) {// 已经生产过了,需要等待
try {
super.wait(); // 等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.setTitle(title);
this.setContent(content);
this.flag = false;// 表示不能生产了
super.notify(); // 唤醒其他等待的线程
}
public synchronized void get() {
if (flag == true) {// 表示不能取
try {
super.wait(); // 等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(this.title + " --> " + this.content);
this.flag = true;// 表示不能取走了
super.notify(); // 唤醒
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
生产类:
public class Producer implements Runnable {
private Info info = null;
public Producer(Info info) {
this.info = info;
}
@Override
public void run() {
// TODO 自动生成的方法存根
for (int x = 0; x < 100; x++) { // 不断的生产
if (x % 2 == 0) {// 是奇数
this.info.set("消费", "购买罐头");
} else {
this.info.set("生产", "生产罐头");
}
}
}
}
消费类:
public class Consumer implements Runnable {
private Info info = null;
public Consumer(Info info) {
this.info = info;
}
@Override
public void run() {
// TODO 自动生成的方法存根
for (int x = 0; x < 100; x++) {
this.info.get();
}
}
}
测试:
public class TestInfo3 {
public static void main(String[] args) {
// TODO 自动生成的方法存根
Info info = new Info();
Producer pro = new Producer(info); // 实例化生产者对象
Consumer con = new Consumer(info); // 实例化消费者对象
new Thread(pro).start(); // 启动线程
new Thread(con).start(); // 启动线程
}
}