В Java мы можем использовать ExecutorService для создания пула потоков и отслеживания хода выполнения асинхронных задач с помощью Future .
Служба исполнителя принимает оба Выполнимые и Вызываемые задачи.
- Работоспособный – Возврат пустоты, ничего.
- Вызываемый – Верните будущее.
1. Служба исполнителей
1.1 Классика Служба исполнителей пример для создания пула потоков с 5 потоками, отправьте две задачи, получите результат из Будущего а также как обработать исключение.
package com.mkyong.concurrency.executor;
import java.util.concurrent.*;
public class ExecutorExample1 {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
// Runnable, return void, nothing, submit and run the task async
executor.submit(() -> System.out.println("I'm Runnable task."));
// Callable, return a future, submit and run the task async
Future futureTask1 = executor.submit(() -> {
System.out.println("I'm Callable task.");
return 1 + 1;
});
/* Before Java 8
executor.submit(new Runnable() {
@Override
public void run() {
System.out.println("I'm Runnable task.");
}
});
Future futureTask1 = executor.submit(new Callable() {
@Override
public Integer call() {
System.out.println("I'm Callable task.");
return 1 + 1;
}
});*/
try {
otherTask("Before Future Result");
// block until future returned a result,
// timeout if the future takes more than 5 seconds to return the result
Integer result = futureTask1.get(5, TimeUnit.SECONDS);
System.out.println("Get future result : " + result);
otherTask("After Future Result");
} catch (InterruptedException e) {// thread was interrupted
e.printStackTrace();
} catch (ExecutionException e) {// thread threw an exception
e.printStackTrace();
} catch (TimeoutException e) {// timeout before the future task is complete
e.printStackTrace();
} finally {
// shut down the executor manually
executor.shutdown();
}
}
private static void otherTask(String name) {
System.out.println("I'm other task! " + name);
}
}
Выход
I'm Runnable task. I'm Callable task. I'm other task! Before Future Result Get future result : 2 I'm other task! After Future Result
2. призывАть всех
2.1 Мы также можем создать список Вызываемых задач и запустить их все с помощью invokeAll
package com.mkyong.concurrency.executor;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class ExecutorExample2 {
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
List> listOfCallable = Arrays.asList(
() -> 1,
() -> 2,
() -> 3);
try {
List> futures = executor.invokeAll(listOfCallable);
int sum = futures.stream().map(f -> {
try {
return f.get();
} catch (Exception e) {
throw new IllegalStateException(e);
}
}).mapToInt(Integer::intValue).sum();
System.out.println(sum);
} catch (InterruptedException e) {// thread was interrupted
e.printStackTrace();
} finally {
// shut down the executor manually
executor.shutdown();
}
}
}
Выход
6
//… Быть обновленным
Скачать Исходный Код
Рекомендации
Оригинал: “https://mkyong.com/java/java-executorservice-examples/”