Thread A
は、計算を実行するループです。ループを実行している別のスレッドの結果へのアクセス
Thread B
は、ループの各繰り返しで生成された結果をThread A
で囲む必要があります。
何もブロックせずにこれを達成する最良の方法は何ですか?
Thread A
は、計算を実行するループです。ループを実行している別のスレッドの結果へのアクセス
Thread B
は、ループの各繰り返しで生成された結果をThread A
で囲む必要があります。
何もブロックせずにこれを達成する最良の方法は何ですか?
ここにはプロデューサー/コンシューマーパターンが必要です。 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
の機能を見てください。他の実装では、それらの多くがあります。
スレッドBの結果を取り込む3番目のスレッドCを追加すると、BlockingQueuesの複数のレイヤーのこのようなチェーンを処理することは可能ですか、より良いアプローチがあるでしょうか? – Ninetou
このようなパイプライン処理は完全に機能しますが、これは一般的なアーキテクチャパターンです。 1つのキュー(スレッドB)のコンシューマは、別のキュー(スレッドC)にサプライヤの役割を果たすこともできます。スレッドA→キュー1→スレッドB→キュー2→スレッドC –
スレッドAが別の計算を行うのを待っている間にスレッドBブロックを使用できますか?また、RxJavaのようなJavaライブラリを使用していますか? –
スレッドAはスレッドAが各反復を完了するのを待つことができます。私はコードをはるかに読みやすくしない限り、組み込みのライブラリに固執することを好むでしょう。アプリケーションはリアルタイム/ほぼリアルタイムで動作するため、パフォーマンスが重要です。 – Ninetou
アップデートごとに新しいスレッドを開始するだけです。 'ExecutorService'を使用してください。 – Multithreader