class Message{
private String title;
private String content;
private boolean flag = true;
//flag == true:表示可以生产,但是不能取走
//flag == flase:表示可以取走,但是不能生产
public synchronized void set(Stringtitle,String content){
if(this.flag == false){
try {
super.wait();
} catch(InterruptedException e) {
e.printStackTrace();
}
}
this.title = title;
try {
Thread.sleep(100);
} catch (InterruptedExceptione) {
e.printStackTrace();
}
this.content = content;
this.flag = false;
super.notify();
}
public synchronized void get(){
if(this.flag == true){
try {
super.wait();
} catch(InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(100);
} catch (InterruptedExceptione) {
e.printStackTrace();
}
System.out.println(this.title+"---> "+this.content);
this.flag = true;
super.notify();
}
}
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();
}
}
·等待:publicfinal void wait() throws InterruptedException;
·唤醒第一个等待线程:public final void notify();
·唤醒全部等待线程:public final void notifyAll()。