#java #java-8 #completion-service
#java #java-8 #завершение-сервис
Вопрос:
Я вызываю некоторые методы параллельно. Я хочу использовать значение, переданное методу, если какой-либо метод выдает исключение.
PS: Пожалуйста, игнорируйте любые синтаксические ошибки.
public static void main() {
Executor executor = Executors.newFixedThreadPool(3);
CompletionService<SomeResult> executorCompletionService = new ExecutorCompletionService<SomeResult>(executor);
List<Future<Integer>> futures = new ArrayList<>();
futures.add(executorCompletionService.submit(() -> someMethod(parameterValueForFirstCall)));
futures.add(executorCompletionService.submit(() -> someMethod(parameterValueForSecondCall)));
futures.add(executorCompletionService.submit(() -> someMethod(parameterValueForThirdCall)));
for (int i=0; i<3; i ){
try {
executorCompletionService.take().get();
} catch(Exception e) {
System.out.println("exception caught :" e.getMessage());
//do something with parameter passed to method that threw exception
}
}
Комментарии:
1. Можете ли вы завершить свой код, чтобы у нас было что-то, что мы могли бы протестировать?
2. Вы пробовали это руководство tutorialspoint.com/java_concurrency /… ?
Ответ №1:
Что-то вроде этого?
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class TestThread {
public static void main(final String[] arguments) throws InterruptedException {
ExecutorService executor = Executors.newFixedThreadPool(3);
ArrayList<FutureTask<Integer>> futures =
new ArrayList<FutureTask<Integer>>();
// Cast the object to its class type
ThreadPoolExecutor pool = (ThreadPoolExecutor) executor;
//Stats before tasks execution
System.out.println("Largest executions: "
pool.getLargestPoolSize());
System.out.println("Maximum allowed threads: "
pool.getMaximumPoolSize());
System.out.println("Current threads in pool: "
pool.getPoolSize());
System.out.println("Currently executing threads: "
pool.getActiveCount());
System.out.println("Total number of threads(ever scheduled): "
pool.getTaskCount());
for (int i=0; i<8; i ){
futures.add( new FutureTask<>(new Task(),i*10) );
}
System.out.println("Submit all tasks.");
for (int i=0; i<8; i ){
executor.submit(futures.get(i));
}
System.out.println("Check every second how many tasks unfinished.");
int done = 1;
while (done>0) {
Thread.sleep(1000);
System.out.println("Next check.");
done = 0;
for (int i=0; i<8; i ) {
System.out.println("Check FT" i);
if (!futures.get(i).isDone()) {
done = 1;
} else {
System.out.println("FT " i " still running?");
}
}
}
//Stats after tasks execution
System.out.println("Core threads: " pool.getCorePoolSize());
System.out.println("Largest executions: "
pool.getLargestPoolSize());
System.out.println("Maximum allowed threads: "
pool.getMaximumPoolSize());
System.out.println("Current threads in pool: "
pool.getPoolSize());
System.out.println("Currently executing threads: "
pool.getActiveCount());
System.out.println("Total number of threads(ever scheduled): "
pool.getTaskCount());
System.out.println("Get FT returns.");
for (int i=0; i<8; i ){
try {
System.out.println("FT" i " returned " futures.get(i).get());
} catch (Exception e) {
System.out.println("FT" i " raised " e);
}
}
executor.shutdown();
}
static class Task implements Runnable {
public void run() {
try {
Long duration = (long) (Math.random() * 5);
System.out.println("Running Task! Thread Name: "
Thread.currentThread().getName());
TimeUnit.SECONDS.sleep(duration);
System.out.println("Task Completed! Thread Name: "
Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}