posts - 29, comments - 0, trackbacks - 0, articles - 0
            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理

          Java 多線程加鎖

          Posted on 2007-05-28 15:39 change 閱讀(216) 評論(0)  編輯  收藏

          以前的同步操作 基本上都是用到 synchronised 關鍵字,類似代碼如下:

          synchronised(obj){

          //dosomething...

          }來做到同步,

          在 JDK5.0  里面有這么一個對象,ReentrantLock,發覺她的加鎖編程的方式非常的適合日常的加鎖習慣,

          EG:

          package com.thread.synchronise;

          import java.util.concurrent.locks.ReentrantLock;

          public class SynchroTest extends Thread{
           private int count = 0;
           private final ReentrantLock lock = new ReentrantLock();
           
           public void run()
           {

          //這里加了幾次鎖,在后面就的要相應的解鎖 幾次
               
          lock.lock();  // block until condition holds
                try {      
                 count++;
                 System.out.println(" count = "+count);
                 try {
              Thread.sleep(3000);
             } catch (InterruptedException e) {
              e.printStackTrace();
             }
                 System.out.println(" count = "+count);
                } finally {
                
          lock.unlock();
                }
           }
           /**
            * @param args
            */
           public static void main(String[] args) {
            // TODO Auto-generated method stub
            SynchroTest st1 = new SynchroTest();
          //  SynchroTest st2 = new SynchroTest();
          //  SynchroTest st3 = new SynchroTest();
            

          //這里不能夠調用   new Thread(st1).run();方法,否則就不是多線程的了
            new Thread(st1).start();
            new Thread(st1).start();
            new Thread(st1).start();
           }

          }

          如果該線程等待某暫時獲取不到的資源,那么我們可以用Condition Object來避免死鎖情況。
          sufficientFunds = lock .newCondition();
          如果條件不滿足:
          sufficientFunds.await();
          這時線程就會釋放鎖并進入blocked狀態,其他線程就有機會執行操作。當其他線程執行完后,就可通知等待的線程繼續執行它的操作了:
          sufficientFunds.signalAll();


          主站蜘蛛池模板: 会理县| 永城市| 伽师县| 光泽县| 伊金霍洛旗| 北京市| 磴口县| 巴东县| 安平县| 龙井市| 台北市| 大连市| 尉氏县| 商河县| 阜新| 嘉荫县| 黑水县| 新龙县| 井陉县| 宣化县| 苗栗市| 桐乡市| 丰城市| 金门县| 上高县| 鹿泉市| 比如县| 当涂县| 沙田区| 平邑县| 萝北县| 西藏| 于都县| 梧州市| 奉贤区| 韶关市| 乌恰县| 陵川县| 安图县| 当阳市| 砚山县|