Java多線程基礎總結七:ReentrantLock

來源:互聯網
上載者:User

之前總結了部分無鎖機制的多線程基礎,理想的狀態當然是利用無鎖同步解決多線程程式設計的問題。但是實際碰到的問題使得很多情 況下,我們不得不藉助鎖同步來保證安全執行緒。自從JDK5開始,有兩種機制來屏蔽代碼塊在並行訪問的幹擾,synchronized關鍵字已經介紹 過了部分內容,所以這次簡單的說說另一種鎖機制:ReentrantLock。

對於synchronized的缺點之前也簡單的說了一些,實際使用中比較煩擾的幾點是:a.只有一個"條件"與鎖相關聯,這對於大量並發線程 的情況是很難管理(等待和喚醒);b.多線程競爭一個鎖時,其餘未得到鎖的線程只能不停的嘗試獲得鎖,而不能中斷。這種情況對於大量的 競爭線程會造成效能的下降等後果。JDK5以後提供了ReentrantLock的同步機制對於前面提的兩種情況有相對的改善。下面我還是寫個小例 子分析一下:

Java代碼

import java.util.concurrent.locks.ReentrantLock;

/**
  * @author: yanxuxin
  * @date: 2010-1-4 
  */
public class ReentrantLockSample {

  public static void main(String[] args) {
  testSynchronized();
  testReentrantLock();
  }

  public static void testReentrantLock() {
  final SampleSupport1 support = new SampleSupport1();
  Thread first = new Thread(new Runnable() {
   public void run() {
   try {
    support.doSomething();
   }
   catch (InterruptedException e) {
    e.printStackTrace();
   }
   }
  });

  Thread second = new Thread(new Runnable() {
   public void run() {
   try {
    support.doSomething();
   }
   catch (InterruptedException e) {
    System.out.println("Second Thread Interrupted without executing counter++,beacuse it waits a long  time.");
   }
   }
  });

  executeTest(first, second);
  }

  public static void testSynchronized() {
  final SampleSupport2 support2 = new SampleSupport2();

  Runnable runnable = new Runnable() {
   public void run() {
   support2.doSomething();
   }
  };

  Thread third = new Thread(runnable);
  Thread fourth = new Thread(runnable);

  executeTest(third, fourth);
  }

  /**
  * Make thread a run faster than thread b,
    * then thread b will be interruted after about 1s.
  * @param a
  * @param b
  */
  public static void executeTest(Thread a, Thread b) {
  a.start();
  try {
   Thread.sleep(100);
   b.start(); // The main thread sleep 100ms, and then start the second thread.

   Thread.sleep(1000);
   // 1s later, the main thread decided not to allow the second thread wait any longer.
   b.interrupt();
  }
  catch (InterruptedException e) {
   e.printStackTrace();
  }
  }
}

abstract class SampleSupport {

  protected int counter;

  /**
  * A simple countdown,it will stop after about 5s.
  */
  public void startTheCountdown() {
  long currentTime = System.currentTimeMillis();
  for (;;) {
   long diff = System.currentTimeMillis() - currentTime;
   if (diff > 5000) {
   break;
   }
  }
  }
}

class SampleSupport1 extends SampleSupport {

  private final ReentrantLock lock = new ReentrantLock();

  public void doSomething() throws InterruptedException {
  lock.lockInterruptibly(); // (1)
  System.out.println(Thread.currentThread().getName() + " will execute counter++.");
  startTheCountdown();
  try {
   counter++;
  }
  finally {
   lock.unlock();
  }
  }
}

class SampleSupport2 extends SampleSupport {

  public synchronized void doSomething() {
  System.out.println(Thread.currentThread().getName() + " will execute counter++.");
  startTheCountdown();
  counter++;
  }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.