少年阿賓

          那些青春的歲月

            BlogJava :: 首頁 :: 聯(lián)系 :: 聚合  :: 管理
            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 閱讀(789) 評論(0)  編輯  收藏 所屬分類: JavaMultithread
          主站蜘蛛池模板: 仙桃市| 长治市| 望江县| 唐海县| 盘山县| 阿克陶县| 鸡东县| 息烽县| 秀山| 平舆县| 高碑店市| 宜宾市| 耿马| 晋江市| 绿春县| 玛纳斯县| 连南| 新巴尔虎右旗| 盐边县| 扶绥县| 筠连县| 英山县| 建瓯市| 凉山| 高雄县| 安康市| 泗水县| 乌拉特后旗| 双鸭山市| 太谷县| 汕尾市| 北安市| 视频| 新密市| 保定市| 咸丰县| 绥江县| 房产| 元江| 辛集市| 英山县|