2016-10-05 200 views
1

我創建了三個線程,如客戶端1,客戶端2,客戶端3與相應的讀取請求「讀取2」,「讀取1」,「讀取3」。我想處理在下述方式讀取請求:第一面向Java多線程併發問題

客戶機2讀1

客戶端1讀2

Client3讀3

我沒有想法來運行一個線程(客戶端2)然後根據讀請求序列線程(client1)等等。有一個條件,我不能在我的程序中使用睡眠。

如果有人知道解決方案,請在上述問題的上下文中提供幫助。

+2

基本上,你要連續的行爲來多線程的。這是倒退的開始。 –

回答

0

根據你的程序的複雜性,它可以使用2 CountDownLatch同步你的線程完成,一個釋放Client1一旦Client2做閱讀和另一個釋放Client3一旦Client1做閱讀。

// Used to release client1 
CountDownLatch startThread1 = new CountDownLatch(1); 
Thread client2 = new Thread(
    () -> { 
     System.out.println("Read 1"); 
     // Release client1 
     startThread1.countDown(); 
    } 
); 
// Used to release client3 
CountDownLatch startThread3 = new CountDownLatch(1); 
Thread client1 = new Thread(
    () -> { 
     try { 
      // Waiting to be released 
      startThread1.await(); 
      System.out.println("Read 2"); 
      // Release client3 
      startThread3.countDown(); 
     } catch (InterruptedException e) { 
      Thread.currentThread().interrupt(); 
     } 
    } 
); 
Thread client3 = new Thread(
    () -> { 
     try { 
      // Waiting to be released 
      startThread3.await(); 
      System.out.println("Read 3"); 
     } catch (InterruptedException e) { 
      Thread.currentThread().interrupt(); 
     } 
    } 
); 
// Start the threads in reverse order intentionally to show that 
// we still have the expected order 
client3.start(); 
client1.start(); 
client2.start(); 

輸出:

Read 1 
Read 2 
Read 3 

這種方法保證得到正確的順序讀取你的線程的啓動順序的任何順序。

+0

感謝您提供解決方案。解決我的問題真的很有幫助 – Ammy