2016-09-03 7 views
2

Thread Aは、計算を実行するループです。ループを実行している別のスレッドの結果へのアクセス

Thread Bは、ループの各繰り返しで生成された結果をThread Aで囲む必要があります。

何もブロックせずにこれを達成する最良の方法は何ですか?

+0

スレッドAが別の計算を行うのを待っている間にスレッドBブロックを使用できますか?また、RxJavaのようなJavaライブラリを使用していますか? –

+0

スレッドAはスレッドAが各反復を完了するのを待つことができます。私はコードをはるかに読みやすくしない限り、組み込みのライブラリに固執することを好むでしょう。アプリケーションはリアルタイム/ほぼリアルタイムで動作するため、パフォーマンスが重要です。 – Ninetou

+0

アップデートごとに新しいスレッドを開始するだけです。 'ExecutorService'を使用してください。 – Multithreader

答えて

3

ここにはプロデューサー/コンシューマーパターンが必要です。 Javaでは、BlockingQueueを使用して実装することができます。

Producer.java

class Producer implements Runnable { 
    private final BlockingQueue<Double> queue; 

    public Producer(BlockingQueue<Double> q) { 
     queue = q; 
    } 

    public void run() { 
     try { 
      while (true) { 
       Double result = calculateResult(); 
       // This call will make the result available to the consumer: 
       queue.put(result); 
      } 
     } catch (InterruptedException ex) { 
      // Handle thread interruption here 
     } 
    } 
} 

class Consumer implements Runnable { 
    private final BlockingQueue<Double> queue; 

    public Consumer(BlockingQueue<Double> q) { 
     queue = q; 
    } 

    public void run() { 
     try { 
      while (true) { 
       // This call Will wait until the next result is available: 
       Double result = queue.take(); 
       // Process the result... 
      } 
     } catch (InterruptedException ex) { 
      // Handle thread interruption here 
     } 
    } 
} 

Consumer.java:ここで消費者に生産者からDouble計算結果を送達するために使用されるArrayBlockingQueue有する例ですProgram.java

class Program { 
    public static void main() { 
     BlockingQueue<Double> queue = new ArrayBlockingQueue<>(); 
     Producer producer = new Producer(queue); 
     Consumer consumer = new Consumer(queue); 
     new Thread(producer).start(); 
     new Thread(consumer).start(); 
    } 
} 

同じキューを共有する複数のコンシューマまたは複数のプロデューサ(またはその両方)を作成できます。これにより、2つ以上のスレッド間で作業のバランスをとることができます。

また、BlockingQueueの機能を見てください。他の実装では、それらの多くがあります。

+0

スレッドBの結果を取り込む3番目のスレッドCを追加すると、BlockingQueuesの複数のレイヤーのこのようなチェーンを処理することは可能ですか、より良いアプローチがあるでしょうか? – Ninetou

+1

このようなパイプライン処理は完全に機能しますが、これは一般的なアーキテクチャパターンです。 1つのキュー(スレッドB)のコンシューマは、別のキュー(スレッドC)にサプライヤの役割を果たすこともできます。スレッドA→キュー1→スレッドB→キュー2→スレッドC –

関連する問題