class Message{
private String title;
private String content;
public synchronized void set(Stringtitle,String content){
this.title = title;
try {
Thread.sleep(100);
} catch (InterruptedExceptione) {
e.printStackTrace();
}
this.content = content;
}
public synchronized void get(){
try {
Thread.sleep(100);
} catch (InterruptedExceptione) {
e.printStackTrace();
}
System.out.println(this.title+"---> "+this.content);
}
}
class Productorimplements Runnable{
private Message msg = null;
public Productor(Message msg){
this.msg = msg;
}
@Override
public void run(){
for(int i = 0;i < 50;i++){
if(i % 2 == 0){
this.msg.set("2012-12-21","世界末日");
}
else{
this.msg.set("付谢", "打扫卫生迎接末日");
}
}
}
}
class Customerimplements Runnable{
private Message msg = null;
public Customer(Message msg){
this.msg = msg;
}
@Override
public void run(){
for(int i = 0;i < 50;i++){
this.msg.get();
}
}
}
public classTestDemo3{
public static void main(String[] args){
Message msg = new Message();
new Thread(newProductor(msg)).start();
new Thread(newCustomer(msg)).start();
}
}
转载于:https://blog.51cto.com/9882931/1617727