练习要求:生产者Producer生产内容Info,消费者Consumer从Info取出内容。
注意:1.生产的Info中,name和content要一一对应.
2.生产者生产一个内容,消费者就取出一个内容,要防止重复取出。
import java.rmi.server.ExportException;
import java.util.TreeMap;
class Info{
private String name = "熊烈";
private String content = "AVBCS";
private boolean flag = true; //作为标记,用来交替等待与唤醒线程
public void setName(String name){
this.name = name;
}
public void setContent(String content){
this.content = content;
}
public synchronized void set(String name,String content){
if (!flag){ //!flag表示 flag != true,即flag = false
try{ //加try是因为wait()会throw一个异常
super.wait(); //等待与唤醒是Object类支持的,所以这里要用super.wait(),使调用set方法的Projector对象休眠
}catch (InterruptedException e){
e.printStackTrace();
}
}
this.setName(name);
/*try{ //加延迟是为了在设置name和content时,看是否会出现问题(错配)
Thread.sleep(300);
}catch (InterruptedException e){
e.printStackTrace();
}*/
this.setContent(content);
flag = false;
super.notify(); //notify()貌似是随机唤醒wait的线程,即此时唤醒调用了get()方法的Consumer对象,该作业里的notify其实是为了唤醒对方
}
public synchronized void get(){
if (flag){
try{
super.wait();
}catch (InterruptedException e){
e.printStackTrace();
}
}
/*try{ //加延迟是为了在设置name和content时,看是否会出现问题(错配)
Thread.sleep(300);
}catch (InterruptedException e){
e.printStackTrace();
}*/
System.out.println(this.name + "-->" + this.content);
flag = true;
super.notify();
}
}
class Producer implements Runnable{
private Info info = null;
public Producer(Info info){
this.info = info;
}
public void run(){
boolean flag = true;
for (int i = 0;i < 10;i++){
if (flag){
this.info.set("李兴华","JAVA讲师");
flag = false;
}else{
this.info.set("MLDN","www.mldn.com");
flag = true;
}
}
}
}
class Consumer implements Runnable{
private Info info = null;
public Consumer(Info info){
this.info = info;
}
public void run(){
for (int i = 0; i < 10; i++){
try{
Thread.sleep(500);
}catch (InterruptedException e){
e.printStackTrace();
}
this.info.get();
}
}
}
public class Main{
public static void main(String[] args) {
Info i = new Info();
Producer pro = new Producer(i);
Consumer con = new Consumer(i);
new Thread(pro).start();
new Thread(con).start();
}
}