package producerandconsumer3;
public class Info {
private String name = "中国";// 信息名称,指定默认值
private String content = "Chain";// 信息内容,指定默认值
private boolean flag = false;// 设置标志位
public synchronized void set(String name, String content) {// 设置信息名称和内容
if (!flag) {// 标志位为false,不可以生产
try {
super.wait();// 等待消费者取走
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.setName(name);
try {
Thread.sleep(300);// 加入延迟
} catch (InterruptedException e) {
e.printStackTrace();
}
this.setContent(content);// 设置信息内容
flag = false;// 修改标志位,表示可以取走
super.notify();// 唤醒等待线程
}
public synchronized void get() {// 取得信息名称和内容
if (flag) {// 标志位为true,不可以取走
try {
super.wait();// 等待生产者生产
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(300);// 加入延迟
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(this.getName() + "-->" + this.getContent());// 输出信息
flag = true;// 修改标志位,表示可以生产
super.notify();// //唤醒等待线程
}
// 取得信息名称
public String getName() {
return name;
}
// 设置信息名称
public void setName(String name) {
this.name = name;
}
// 取得信息内容
public String getContent() {
return content;
}
// 设置信息内容
public void setContent(String content) {
this.content = content;
}
}