少年阿賓

          那些青春的歲月

            BlogJava :: 首頁(yè) :: 聯(lián)系 :: 聚合  :: 管理
            500 Posts :: 0 Stories :: 135 Comments :: 0 Trackbacks
          下面的例子通過(guò)wait()來(lái)取代忙等待機(jī)制,當(dāng)收到通知消息時(shí),notify當(dāng)前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 閱讀(783) 評(píng)論(0)  編輯  收藏 所屬分類: JavaMultithread
          主站蜘蛛池模板: 乌恰县| 根河市| 营口市| 宝清县| 平顺县| 喀喇| 武穴市| 常山县| 龙川县| 石泉县| 镇赉县| 宁陵县| 疏勒县| 尚义县| 桓台县| 隆回县| 个旧市| 蓬溪县| 益阳市| 桂林市| 新密市| 梅州市| 陆河县| 卫辉市| 准格尔旗| 开化县| 策勒县| 贵阳市| 仙桃市| 中阳县| 白银市| 泰安市| 瑞安市| 贵阳市| 河北区| 海南省| 绥江县| 昌吉市| 阿鲁科尔沁旗| 双城市| 嘉祥县|