Executor in java example

Java Executor Framework Tutorial and Example

Java Executor Framework is a framework that manages threads to start, execute and terminate. Java Executor Framework provides different classes and methods that manage to create thread pool of fixed and variable sizes. Java Executor Framework provides Executor, ExecutorService and Executors in java.util.concurrent API. Executors creates the instance of ExecutorService that executes the submitted task. Executor can be overridden to implement execute() method according to our requirement. ExecutorService returns Future object that check the health of running task.

Java Executor Example

java.util.concurrent.Executor is an interface and introduced in JDK 5 and is the part of executor framework. Executor executes the submitted task. Executor gives the opportunity how we want to decouple the submitted task. To use Executor we need to create a class that will implement Executor interface. Executor can be implemented according to our task. If we want to implement Executor to run thread normally then we can do like
SimpleExecutor.java

class SimpleExecutor implements Executor < public void execute(Runnable r) < r.run(); >>

Now we consider one typical example in which we will run each thread sequentially. For that find a runnable thread.
RunnableThread.java

package com.concretepage; public class RunnableThread implements Runnable < String seq = null; public RunnableThread(String seq)< this.seq = seq; >@Override public void run() < for (int cnt = 0; cnt &lt 5; cnt++) < System.out.println(seq+":" + cnt); >> >

We have implemented an inner class SequentialExecutor. Using ArrayDeque, we are scheduling each task one by one.
ExecutorDemo.java

package com.concretepage; import java.util.ArrayDeque; import java.util.Queue; import java.util.concurrent.Executor; public class ExecutorDemo < public static void main(String[] args) < RunnableThread t1 = new RunnableThread("One"); RunnableThread t2 = new RunnableThread("Two"); Executor executor = new SequentialExecutor(); executor.execute(t1); executor.execute(t2); >> class SequentialExecutor implements Executor < final Queue&ltRunnable&gt queue = new ArrayDeque&ltRunnable&gt(); Runnable task; public synchronized void execute(final Runnable r) < queue.offer(new Runnable() < public void run() < try < r.run(); >finally < next(); >> >); if (task == null) < next(); >> private synchronized void next() < if ((task = queue.poll()) != null) < new Thread(task).start(); >> >
Executing thread one:0 Executing thread one:1 Executing thread one:2 Executing thread one:3 Executing thread one:4 Executing thread two:0 Executing thread two:1 Executing thread two:2 Executing thread two:3 Executing thread two:4

ExecutorService in Java

java.util.concurrent.ExecutorService has been introduced in JDK 5 and is the part of executor framework. ExecutorService is an Executor than can manage shutdown of executing subtask. It also provides Future object by which we check the progress of running task. ExecutorService has two method to terminate the task shutdown() and shutdownNow(). The difference between these two are that shutdown method will allow previously submitted task to execute and will accept no new task whereas shutdownNow method will not execute any task which has not started yet and even attempt to stop running task also. ExecutorService can be instantiated as below.

ExecutorService exService = Executors.newSingleThreadExecutor();

Executors in Java

java.util.concurrent.Executors has been introduced in JDK 5 and is the part of executor framework. Executors is a class that provides ExecutorService. ExecutorService has different methods like newCachedThreadPool(), newScheduledThreadPool() and newCachedThreadPool() that serves different purpose to create thread pool. newCachedThreadPool() creates a pool with no fixed size whereas newFixedThreadPool creates a fixed size pool. newScheduledThreadPool() creates a thread pool that can schedule thread after the given time.

Читайте также:  Изображения

Example of ExecutorService and Executors in Java

Find the simple example that will use both ExecutorService and Executors. We are using here newFixedThreadPool() that will return ExecutorService object.
ExecutorsDemo.java

package com.concretepage; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ExecutorsDemo < public static void main(String[] args) < RunnableThread t = new RunnableThread("Executing thread"); ExecutorService exService = Executors.newFixedThreadPool(1); exService.execute(t); >>
Executing thread one:0 Executing thread one:1 Executing thread one:2 Executing thread one:3 Executing thread one:4

Источник

Многопоточность в Java: ExecutorService

До Java 5 для организации работы с несколькими потоками приходилось использовать сторонние имплеменации пулинга или писать свой. С появлением ExecutorService такая необходимость отпала.

ExecutorService исполняет асинхронный код в одном или нескольких потоках. Создание инстанса ExecutorService’а делается либо вручную через конкретные имплементации ( ScheduledThreadPoolExecutor или ThreadPoolExecutor ), но проще будет использовать фабрики класса Executors . Например, если надо создать пул с 2мя потоками, то делается это так:

Если требуется использовать кэширующий пул потоков, который создает потоки по мере необходимости, но переиспользует неактивные потоки (и подчищает потоки, которые были неактивные некоторое время), то это задается следующим образом:

Теперь небольшой пример. Допустим, надо запустить какой-нибудь код асинхронно 10 раз. Основываясь на вышесказанном, код будет выглядеть так:

ExecutorService service = Executors.newCachedThreadPool();
for ( int i = 0; i < 10; i++) service.submit( new Runnable() public void run() // snip. piece of code
>
>);
>

Метод submit также возвращает объект Future , который содержит информацию о статусе исполнения переданного Runnable или Callable (который может возвращать значение). Из него можно узнать выполнился ли переданный код успешно, или он еще выполняется. Вызов метода get на объекте Future возвратит значение, который возвращает Callable (или null , если используется Runnable ). Метод имеет 2 checked-исключения: InterruptedException , который бросается, когда выполнение прервано через метод interrupt() , или ExecutionException если код в Runnable или Callable бросил RuntimeException , что решает проблему поддержки исключений между потоками.

ScheduledExecutorService

Иногда требуется выполнение кода асихронно и периодически или требуется выполнить код через некоторое время, тогда на помощь приходит ScheduledExecutorService . Он позволяет поставить код выполняться в одном или нескольких потоках и сконфигурировать интервал или время, на которое выполненение будет отложено. Интервалом может быть время между двумя последовательными запусками или время между окончанием одного выполнения и началом другого. Методы ScheduledExecutorService возвращают ScheduledFuture , который также содержит значение отсрочки для выполнения ScheduledFuture .

Например, если требуется отложить выполнение на 5 секунд, потребуется следующий код:

ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.schedule( new Runnable() < . >, 5, TimeUnit.SECONDS);

ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.scheduleAtFixedRate( new Runnable() < . >, 0, 1, TimeUnit.SECONDS);

ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.scheduleWithFixedDelay( new Runnable() < . >, 0, 1, TimeUnit.SECONDS);

Источник

Оцените статью