リスト内のすべてのオブジェクトに対して新しいスレッドを開始し、それらに対してメソッドを呼び出しています。私が呼び出すメソッドは、次のように保存したい値を返します。
public int[] benchAll(){
int[] numbers = new int[things.size()];
for (final Thing thing: things) {
final Generator generator = new Generator();
new Thread(
() -> generator.benchmark(thing)
).start();
generators.add(generator);
}
return numbers;
}
benchmark()
では、このメソッドで返すために、他のスレッドのすべての戻り値を保存するにはどうすればよいbenchAll()
ですか?
あなたの助けをいただければ幸いです。
java.util.concurrent.ExecutorService
Java仕様にあるように使用します。
終了を管理するメソッドと、1つ以上の非同期タスクの進行状況を追跡するためのFutureを生成できるメソッドを提供するエグゼキューター。
したがって、の実装を使用するとExecutorService
、指定された数のスレッドですべてのタスクを非同期または同期で実行できます。そのためには、Callable
オブジェクトのリストを作成し、それをinvokeAll
のオブジェクトのメソッドに渡す必要がありますExecutorService
。invokeAll
メソッドは、Futureオブジェクトのリストのリストを返します(各Futureオブジェクトは各タスクを表し、順序はメソッドにCallable
渡されたリストに入力したものと同じですinvokeAll
)。これにより、タスクのすべての結果をループして出力できます。
のExecutors
さまざまなインスタンスを返すクラスの利用可能なすべてのメソッドを読む必要がExecutorService
あるため、自分に合ったものを選択してください。
このようにして、N個のタスクをM個のスレッドで非同期に実行でき、すべてのスレッドが終了すると、各タスクの完了情報/ステータスを提供するFutureオブジェクトのリストが表示されます。
この結果は、他の結果/データとマージして、メソッドから返すことができます。
以下の疑似例を確認してください。
try {
List<Callable<Object>> callableList = new ArrayList<Callable<Object>>();
callableList.add(null); /*Add instance of Callable*/
callableList.add(null); /*Add instance of Callable*/
callableList.add(null); /*Add instance of Callable*/
//Specify how many threads you want or need to operate. Read other methods of Executors which return different instances of ExecutorService
final ExecutorService service = Executors.newFixedThreadPool(3);
//This will invoke all your N tasks in specified M threads ...
List<Future<String[]>> futureObjects = service.invokeAll(callableList); //futureObjects will contain result of each thread execution
} catch (InterruptedException e) {
e.printStackTrace();
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加