2017-01-28 138 views
0

ReentrantLock在創建Lock對象時提供了boolean fair標誌。java中的同步 - new ReentrantLock(true)和new ReentrantLock(false)產生相同的結果?

  1. fairtrue

    線程提供獲得基礎上,他們一直在等待的時間臨界區。

  2. fairfalse

    有給了臨界區的線程沒有具體政策。

下面是我爲同一代碼:

public class ThreadDemo { 
    private Lock lock = new ReentrantLock(false); 

    public static void main(String[] args) { 
     ThreadDemo td = new ThreadDemo(); 
     Thread[] tArr = new Thread[5]; 
     // Creates 5 thread and stores them in a array 
     for (int i = 0; i < 5; i++) { 
      tArr[i] = new Thread(() -> { 
       td.enterCriticalSection(new Date().getTime()); 
      }, "Thread " + i); 
     } 
     // Iterate through the array and start it. 
     for (int i = 0; i < 5; i++) { 
      tArr[i].start(); 
      try { 
       Thread.currentThread().sleep(1000); 
      } catch (InterruptedException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

     } 
    } 

    public void enterCriticalSection(long waitTime) { 
     System.out.println(Thread.currentThread().getName() + " requesting critical section at:" 
       + new SimpleDateFormat("HH:mm:ss:SSS").format(new Date().getTime())); 
     // Gets Lock 
     lock.lock(); 

     try { 
      /* 
      * Logs the entry time in critical section and waiting period for 
      * the thread 
      */ 
      System.out.println(Thread.currentThread().getName() + " in critical section at " 
        + new SimpleDateFormat("HH:mm:ss:SSS").format(new Date().getTime())); 
      Thread.currentThread().sleep(5000); 
     } catch (InterruptedException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } finally { 
      // Releases lock 
      lock.unlock(); 
     } 

     } 
} 

但不管公平爲真公平假我得到相同的結果,即線程這等待最長時間得到關鍵部分

Thread 0 requesting critical section at:01:57:48:562 
Thread 0 in critical section at 01:57:48:563 
Thread 1 requesting critical section at:01:57:49:520 
Thread 2 requesting critical section at:01:57:50:520 
Thread 3 requesting critical section at:01:57:51:520 
Thread 4 requesting critical section at:01:57:52:520 
Thread 1 in critical section at 01:57:53:564 
Thread 2 in critical section at 01:57:58:564 
Thread 3 in critical section at 01:58:03:565 
Thread 4 in critical section at 01:58:08:566 

回答

2

全部fair false的意思是說,鎖會讓線程在它想要的。有了少量的線程,它可能恰好是他們一直在等待的順序,但它不能保證這一點。

+1

我嘗試了10-20個線程,並嘗試了它多次,甚至我認爲它會根據請求的順序爲關鍵部分分配鎖定號碼 –

+2

@DharmvirTiwari javadoc說'ReentrantLock(true )'必須創建一個公平的鎖,但它不會說'ReentrantLock(false)'必須創建一個_unfair_鎖。如果你的JRE即使在'fair == false'的情況下似乎也能創建一個公平的鎖,那麼這並不能證明它存在任何問題。 –

相關問題