У меня есть блок кода, который нужно запускать параллельно в разных потоках, используя
Код: Выделить всё
CompletableFuture
Код: Выделить всё
ExecutorService
Код: Выделить всё
SingleThreadExecutor#submit()
I want to ensure all parallel runs of this block of code get their own thread and run all their operations on that thread.
Basically the block of code should act like synchronous code, but have multiple instance of this block running in parallel, each instance on it's own thread.
Currently, the program just idles when we make a call from the
Код: Выделить всё
Service
Код: Выделить всё
SingleThreadExecutor
Код: Выделить всё
ArrayList futures = new ArrayList();
for (int i = 0; i < SIZE; i++) {
ExecutorService executor = Executors.newSingleThreadExecutor();
CompletableFuture future = CompletableFuture.runAsync(() -> {
Future stringListFuture = myStringService.getStringList(executor);
// We begin stalling once the next line gets hit.
List stringList = stringListFuture.get();
Future integerDataFuture = myIntegerService.getInteger(executor);
Integer integerData = integerDataFuture.get();
executor.shutdown();
}, executor);
futures.add(future);
}
CompletableFuture completableFutures = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
completableFutures.join();
// Do something after all blocks of code have finished running in parallel.
Код: Выделить всё
class MyStringFuture {
public Future getStringList(ExecutorService executor) {
// Could these nested uses of the same executor be the problem?
Future doubeDataFuture = doubleDataService.getFuture();
Double doubleData = doubeDataFuture.get(executor);
Call data = retrofit.create(Api.class).getData(doubleData);
return executor.submit(() -> data.execute().body());
}
}
Источник: https://stackoverflow.com/questions/781 ... iple-times