- ExecutorService в Java
- Пример
- Реализации
- ThreadPoolExecutor
- ThreadPoolExecutor выполняет указанные задачи, используя один из своих внутренних потоков пула. Создание threadPoolExecutor
- ScheduledThreadPoolExecutor
- Использование
- execute(Runnable)
- submit(Runnable)
- submit(Callable)
- invokeAny()
- Как отменить задачу?
- Завершение
- Interface ExecutorService
- Usage Examples
- Interface ExecutorService
- Usage Examples
ExecutorService в Java
Язык программирования Java очень эффективно работает с многопоточными приложениями, которые требуют, чтобы задачи выполнялись одновременно в потоке. Любому приложению становится сложно одновременно выполнять большое количество потоков. Итак, чтобы преодолеть эту проблему, Java поставляется с ExecutorService, который является подчиненным интерфейсом платформы Executors.
В больших многопоточных приложениях одновременно будут выполняться сотни потоков. Следовательно, имеет смысл отделить создание потока от управления потоками в приложении.
Исполнитель – это фреймворк, который помогает вам создавать потоки в приложении и управлять ими. Фреймворк исполнителя поможет вам в следующих задачах.
- Создание потоков: он предоставляет множество методов для создания потоков, которые помогают в одновременном запуске ваших приложений.
- Управление потоками: он также управляет жизненным циклом потока. Вам не нужно беспокоиться о том, активен ли поток, занят или мертв, прежде чем отправлять задачу на выполнение.
- Отправка и выполнение задач: платформа Executor предоставляет методы для отправки задач в пуле потоков, а также дает возможность решать, будет ли поток выполняться или нет.
Пример
Это субинтерфейс структуры исполнителя, который добавляет определенные функции для управления жизненным циклом потока приложения. Он также предоставляет метод submit(), который может принимать как запускаемые, так и вызываемые объекты.
В следующем примере мы создадим ExecutorService с одним потоком, а затем отправим задачу для выполнения внутри потока.
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Example < public static void main(String[] args) < System.out.println(" Inside : " + Thread.currentThread().getName()); System.out.println("creating ExecutorService"); ExecutorService executorservice = Executors.newSingleThreadExecutor(); System.out.println("creating a runnable"); Runnable runnable =() ->< System.out.println("inside: "+ Thread.currentThread().getName()); >; System.out.println("submit the task specified by the runnable to the executorservice"); executorservice.submit(runnable); > >
Output: Inside: main creating ExecutorService creating a runnable submit the task specified by the runnable to the executorservice inside: pool-1-thread-1
Вышеупомянутая программа показывает, как мы можем создать ExecutorService и выполнить задачу внутри исполнителя. Если задача отправлена на выполнение, а поток в настоящее время занят выполнением другой задачи, то задача будет ждать в очереди, пока поток не освободится для ее выполнения.
Когда вы запустите указанную выше программу, она никогда не завершится. Вам нужно будет отключить ее явно, поскольку служба исполнителя продолжает прослушивать новые задачи.
Реализации
ExecutorService очень похож на пул потоков. Фактически, реализация ExecutorService в пакете java.util.concurrent является реализацией пула потоков. ExecutorService имеет следующие реализации в пакете java.util.concurrent:
ThreadPoolExecutor
ThreadPoolExecutor выполняет указанные задачи, используя один из своих внутренних потоков пула.
Создание threadPoolExecutor
int corePoolSize = 5; int maxPoolSize = 10; long keepAliveTime = 5000; ExecutorService threadPoolExecutor = new threadPoolExecutor( corePoolSize, maxPoolSize, keepAliveTime, TimeUnit.MILLISECONDS, new LinkedBlockingQueue());
ScheduledThreadPoolExecutor
Java.util.concurrent.ScheduledThreadPoolExecutor – это ExecutorService, который может планировать выполнение задач после задержки или повторное выполнение с фиксированным интервалом времени между каждым выполнением.
ScheduledExecutorService scheduledexecutorservice = Executors.newScheduledThreadPool (5); ScheduledFuture scheduledfuture = scheduledExecutorService.schedule(new Callable() < public Object call() throws Exception< System.out.println("executed"); return "called"; >>, 5, TimeUnit.SECONDS);
Использование
Есть несколько разных способов делегировать задачи ExecutorService.
execute(Runnable)
Выполнение ExecutorService execute(Runnable) принимает объект java.lang.Runnable и выполняет его асинхронно.
ExecutorService executorService = Executors.newSingleThreadExecutor(); executorService.execute(new Runnable() < public void run()< System.out.println("asynchronous task"); >>); executorService.shutdown();
Невозможно получить результат выполнения Runnable, для этого вам нужно использовать Callable.
submit(Runnable)
Метод Java ExecutorService submit(Runnable) принимает реализацию Runnable и возвращает будущий объект. Будущий объект можно использовать для проверки завершения выполнения Runnable.
Future future = executorService.submit(new Runnable() < public void run()< System.out.println(:asynchronous task"); >>); future.get(); //returns null if the task is finished correctly.
submit(Callable)
Метод submit(Callable) Java ExecutorService аналогичен submit(Runnable), но для него используется Java Callable вместо Runnable.
Future future = executorService.submit(new Callable() < public Object call() throws Exception< System.out.println("Asynchronous callable"); return "Callable Result"; >>); System.out.println("future.get() EnlighterJSRAW" data-enlighter-language="java">Output: Asynchroous callable future.get = Callable Result
invokeAny()
Метод invokeAny() принимает коллекцию вызываемых объектов. Вызов этого метода не возвращает будущего, но возвращает результат одного из вызываемых объектов.
ExecutorService executorService = Executors.newSingleThreadExecutor(); Set> callables = new HashSet>(); callables.add(new Callable() < public String call() throws Exception< return"task A"; >>); callables.add(new Callable() < public String call() throws Exception< return"task B"; >>); callables.add(new Callable() < public String call() throws Exception< return"task C"; >>); String result = executorService.invokeAny(callables); System.out.println(«result EnlighterJSRAW» data-enlighter-language=»java»>ExecutorService executorService = Executors.newSingleThreadExecutor(); Set> callables = new HashSet>(); callables.add(new Callable() < public String call() throws Exception< return "Task A"; >>); callables.add(new Callable() < public String call() throws Exception< return "Task B"; >>); callables.add(new Callable() < public String call() throws Exception< return "Task C"; >>); List
public interface Runnable
Основное различие между ними заключается в том, что метод call() может возвращать объект из вызова метода. И метод call() может вызвать исключение, а метод run() – нет.
Как отменить задачу?
Вы можете отменить задачу, отправленную в ExecutorService, просто вызвав метод отмены в будущем, отправленном при отправке задачи.
Завершение
Чтобы потоки не запускались даже после завершения выполнения, следует закрыть ExecutorService. Чтобы завершить потоки внутри ExecutorService, вы можете вызвать метод shutdown().
Interface ExecutorService
An Executor that provides methods to manage termination and methods that can produce a Future for tracking progress of one or more asynchronous tasks.
An ExecutorService can be shut down, which will cause it to reject new tasks. Two different methods are provided for shutting down an ExecutorService . The shutdown() method will allow previously submitted tasks to execute before terminating, while the shutdownNow() method prevents waiting tasks from starting and attempts to stop currently executing tasks. Upon termination, an executor has no tasks actively executing, no tasks awaiting execution, and no new tasks can be submitted. An unused ExecutorService should be shut down to allow reclamation of its resources.
Method submit extends base method Executor.execute(Runnable) by creating and returning a Future that can be used to cancel execution and/or wait for completion. Methods invokeAny and invokeAll perform the most commonly useful forms of bulk execution, executing a collection of tasks and then waiting for at least one, or all, to complete. (Class ExecutorCompletionService can be used to write customized variants of these methods.)
The Executors class provides factory methods for the executor services provided in this package.
Usage Examples
Here is a sketch of a network service in which threads in a thread pool service incoming requests. It uses the preconfigured Executors.newFixedThreadPool(int) factory method:
class NetworkService implements Runnable < private final ServerSocket serverSocket; private final ExecutorService pool; public NetworkService(int port, int poolSize) throws IOException < serverSocket = new ServerSocket(port); pool = Executors.newFixedThreadPool(poolSize); >public void run() < // run the service try < for (;;) < pool.execute(new Handler(serverSocket.accept())); >> catch (IOException ex) < pool.shutdown(); >> > class Handler implements Runnable < private final Socket socket; Handler(Socket socket) < this.socket = socket; >public void run() < // read and service request on socket >>
The following method shuts down an ExecutorService in two phases, first by calling shutdown to reject incoming tasks, and then calling shutdownNow , if necessary, to cancel any lingering tasks:
void shutdownAndAwaitTermination(ExecutorService pool) < pool.shutdown(); // Disable new tasks from being submitted try < // Wait a while for existing tasks to terminate if (!pool.awaitTermination(60, TimeUnit.SECONDS)) < pool.shutdownNow(); // Cancel currently executing tasks // Wait a while for tasks to respond to being cancelled if (!pool.awaitTermination(60, TimeUnit.SECONDS)) System.err.println("Pool did not terminate"); >> catch (InterruptedException ex) < // (Re-)Cancel if current thread also interrupted pool.shutdownNow(); // Preserve interrupt status Thread.currentThread().interrupt(); >>
Memory consistency effects: Actions in a thread prior to the submission of a Runnable or Callable task to an ExecutorService happen-before any actions taken by that task, which in turn happen-before the result is retrieved via Future.get() .
Interface ExecutorService
An Executor that provides methods to manage termination and methods that can produce a Future for tracking progress of one or more asynchronous tasks.
An ExecutorService can be shut down, which will cause it to reject new tasks. Two different methods are provided for shutting down an ExecutorService . The shutdown() method will allow previously submitted tasks to execute before terminating, while the shutdownNow() method prevents waiting tasks from starting and attempts to stop currently executing tasks. Upon termination, an executor has no tasks actively executing, no tasks awaiting execution, and no new tasks can be submitted. An unused ExecutorService should be shut down to allow reclamation of its resources.
Method submit extends base method Executor.execute(Runnable) by creating and returning a Future that can be used to cancel execution and/or wait for completion. Methods invokeAny and invokeAll perform the most commonly useful forms of bulk execution, executing a collection of tasks and then waiting for at least one, or all, to complete. (Class ExecutorCompletionService can be used to write customized variants of these methods.)
The Executors class provides factory methods for the executor services provided in this package.
Usage Examples
Here is a sketch of a network service in which threads in a thread pool service incoming requests. It uses the preconfigured Executors.newFixedThreadPool(int) factory method:
class NetworkService implements Runnable < private final ServerSocket serverSocket; private final ExecutorService pool; public NetworkService(int port, int poolSize) throws IOException < serverSocket = new ServerSocket(port); pool = Executors.newFixedThreadPool(poolSize); >public void run() < // run the service try < for (;;) < pool.execute(new Handler(serverSocket.accept())); >> catch (IOException ex) < pool.shutdown(); >> > class Handler implements Runnable < private final Socket socket; Handler(Socket socket) < this.socket = socket; >public void run() < // read and service request on socket >>
An ExecutorService may also be established and closed (shutdown, blocking until terminated) as follows; illustrating with a different Executors factory method:
try (ExecutorService e = Executors.newWorkStealingPool()) < // submit or execute many tasks with e . >
Further customization is also possible. For example, the following method shuts down an ExecutorService in two phases, first by calling shutdown to reject incoming tasks, and then calling shutdownNow , if necessary, to cancel any lingering tasks:
void shutdownAndAwaitTermination(ExecutorService pool) < pool.shutdown(); // Disable new tasks from being submitted try < // Wait a while for existing tasks to terminate if (!pool.awaitTermination(60, TimeUnit.SECONDS)) < pool.shutdownNow(); // Cancel currently executing tasks // Wait a while for tasks to respond to being cancelled if (!pool.awaitTermination(60, TimeUnit.SECONDS)) System.err.println("Pool did not terminate"); >> catch (InterruptedException ex) < // (Re-)Cancel if current thread also interrupted pool.shutdownNow(); // Preserve interrupt status Thread.currentThread().interrupt(); >>
Memory consistency effects: Actions in a thread prior to the submission of a Runnable or Callable task to an ExecutorService happen-before any actions taken by that task, which in turn happen-before the result is retrieved via Future.get() .