少年阿賓

          那些青春的歲月

            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 閱讀(789) 評論(0)  編輯  收藏 所屬分類: JavaMultithread
          主站蜘蛛池模板: 郴州市| 桐庐县| 江永县| 荔浦县| 东兴市| 波密县| 商丘市| 潜山县| 平湖市| 清流县| 隆化县| 阳西县| 甘德县| 包头市| 樟树市| 濮阳县| 府谷县| 阿尔山市| 徐闻县| 东莞市| 灵宝市| 偃师市| 淅川县| 遂昌县| 逊克县| 吕梁市| 凭祥市| 南召县| 宜兰市| 镇远县| 仪征市| 泾川县| 西华县| 河北省| 革吉县| 衡水市| 奉新县| 横峰县| 修文县| 巴楚县| 榆社县|