packageorg.lx.multithreading;classInfo//定义信息类{privateStringname="罗星";//定义name属性privateStringcontent="JAVA初学者";//定义content属性privatebooleanflag=false;//设置标志位publicsynchronizedvoidset(Stringname,Stringcontent){if(!flag){//方法每次执行的时候都检查一下标志位状态,从而判断时候进行生产try{super.wait();
}catch(InterruptedExceptione){
e.printStackTrace();
}
}this.setName(name);//设置名称try{
Thread.sleep(300);
}catch(InterruptedExceptione){
e.printStackTrace();
}this.setContent(content);//设置内容flag=false;//改变标志位,表示可以取走super.notify();//唤醒线程}publicsynchronizedvoidget(){if(flag){方法每次执行的时候都检查一下标志位状态,从而判断时候进行取出try{super.wait();
}catch(InterruptedExceptione){
e.printStackTrace();
}
}try{
Thread.sleep(300);
}catch(InterruptedExceptione){
e.printStackTrace();
}
System.out.println(this.getName()+"-->"+this.getContent());
flag=true;//改变标志位,表示可以生成super.notify();
}publicvoidsetName(Stringname){this.name=name;
}publicStringgetName(){returnthis.name;
}publicvoidsetContent(Stringcontent){this.content=content;
}publicStringgetContent(){returnthis.content;
}
}classProducerimplementsRunnable//通过Runnable实现多线程{publicInfoinfo=null;//保存Info引用publicProducer(Infoinfo){this.info=info;
}publicvoidrun(){booleanflag=false;//定义标记位for(inti=0;i<50;i++){if(flag){this.info.set("罗星","JAVA初学者");
flag=false;
}else{this.info.set("Solitary","Coder");
flag=true;
}
}
}
};classConsumerimplementsRunnable{//消费者类privateInfoinfo=null;publicConsumer(Infoinfo){this.info=info;
}publicvoidrun(){for(inti=0;i<50;i++){this.info.get();
}
}
};//测试代码publicclassMultiThreading
{publicstaticvoidmain(String[]args){
Infoinfo=newInfo();//实例化Info对象Producerpro=newProducer(info);//生产者Consumercon=newConsumer(info);//消费者newThread(pro).start();newThread(con).start();
}
}