少年阿賓

          那些青春的歲月

            BlogJava :: 首頁 :: 聯系 :: 聚合  :: 管理
            500 Posts :: 0 Stories :: 135 Comments :: 0 Trackbacks
           Java所有的類都具有線程的潛力,Java賦予的每個對象一個鎖,在計算機內部工作在同一時間,只有一個對象可以持有鎖,也就是說程序在同一時間只有一個程序可以運行,這里我把對象比作是一個小的程序。而多處理器,那么就另當別論了。

                在這里我們首先學習一下公共方法wait,notify,notifyAll。

                wait方法可以使在當前線程的對象等待,直到別的線程調用此對象的notify或notifyAll方法(注意:調用的是此對象的notify和notifyAll),并且當前運行的線程必須具有此對象的對象監視器

          package com.abin.lee.thread.thread;

          public class CarryTask extends Thread {
           public void run() {
                  try {
                      synchronized (this) {
                          Thread t = Thread.currentThread();
                          System.out.println(t.getId() + t.getName() + ":task start, wait for notify...");
                          this.wait();
                          System.out.println(t.getId() + t.getName() + ":task continue...");
                      }
                  } catch (InterruptedException ex) {
                     System.out.println(CarryTask.class.getName());
                  }
              }


          }





          package com.abin.lee.thread.thread;

          public class CarryWait {
           public static void main(String[] args) throws InterruptedException {
            CarryTask task = new CarryTask();
            Thread t = Thread.currentThread();
            System.out.println(t.getId() + t.getName() + ":task start...");
            task.start();
            Thread.sleep(2000);
            synchronized (task) {
             System.out.println("id="+Thread.currentThread().getId()+",Name="+Thread.currentThread().getName()+",task="+task+",notify");
             task.notify();
            }
           }

          }





          http://www.iteye.com/topic/1124814
          posted on 2013-01-16 23:46 abin 閱讀(406) 評論(0)  編輯  收藏 所屬分類: JavaMultithread
          主站蜘蛛池模板: 泸水县| 班戈县| 贵港市| 吉安市| 游戏| 阆中市| 长武县| 云安县| 双城市| 乐安县| 丹江口市| 遵化市| 望奎县| 南昌县| 东丰县| 乐安县| 桦川县| 梅河口市| 长岛县| 长岭县| 白水县| 淄博市| 深州市| 雅江县| 海安县| 丹巴县| 新建县| 绿春县| 玉环县| 定日县| 舒城县| 康乐县| 浦东新区| 浦北县| 永德县| 建平县| 大同县| 启东市| 正蓝旗| 东乡县| 建阳市|