少年阿宾

那些青春的岁月

  BlogJava :: 首页 :: 联系 :: 聚合  :: 管理
  500 Posts :: 0 Stories :: 135 Comments :: 0 Trackbacks
下面的例子通过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();
}
}
posted on 2012-11-17 01:01 abin 阅读(775) 评论(0)  编辑  收藏 所属分类: JavaMultithread

只有注册用户登录后才能发表评论。


网站导航: