下面的例子通过wait()来取代忙等待机制,当收到通知消息时,notify当前Monitor类线程。 package com.abin.lee.servlet.mythread.runnable;
import java.util.concurrent.TimeUnit;
public class MyObject implements Runnable{
private Monitor monitor;
public MyObject(Monitor monitor) {
this.monitor=monitor;
}
public void run(){
try {
System.out.println("beforeTimeUnit.SECONDS="+System.currentTimeMillis());
TimeUnit.SECONDS.sleep(3);
System.out.println("i am going");
monitor.getMessage();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package com.abin.lee.servlet.mythread.runnable;
public class Monitor implements Runnable{
private volatile boolean go=false;
public synchronized void getMessage(){
System.out.println("beforenotify getMessage="+System.currentTimeMillis());
go=true;
notify();
System.out.println("afternotify getMessage="+System.currentTimeMillis());
}
public synchronized void watching() throws InterruptedException{
System.out.println("beforewait watching="+System.currentTimeMillis());
while(go==false)
wait();
System.out.println("he has gone");
}
public void run(){
try {
watching();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package com.abin.lee.servlet.mythread.runnable;
public class Wait {
public static void main(String[] args) {
Monitor monitor=new Monitor();
MyObject obj=new MyObject(monitor);
new Thread(obj).start();
new Thread(monitor).start();
}
}