2016-10-05 4 views
1

私は、対応する読み取り要求 "read 2"、 "read 1"、 "read 3"を持つclient1、client2、client3のような3つのスレッドを作成しました。最初Javaマルチスレッド同時実行の問題に直面

クライアント2が1

はClient1が

クライアント3 iは、スレッド(クライアント2)を実行するためのアイデアを持っていない

3を読んで2を読んで読んで:私は、次のように読み取り要求を処理したかったですスレッド(client1)などの読み取り要求sequence.Thereに基づいて私は私のプログラムでスリープを使用することはできませんが1つの条件があります。

誰かが解決策を知っている場合は、上記の問題のコンテキストでヘルプを提供してください。

+2

基本的に、複数のスレッドから順次動作が発生するようにしたい。それは逆に始まっています。 –

答えて

0

は、あなたのプログラムの複雑さに応じて、それはClient2が読み終わったとClient1たらClient3を解放するために別のものを読み終わった後Client1を解放するために、あなたのスレッド、1を同期させるために2 CountDownLatchを使用して行うことができます。

// 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