Java scheduler thread pool

Пример планировщика Java. Пример ScheduledExecutorService, Пример ScheduledThreadPoolExecutor, Исполнители Планировщик потоков newScheduledThreadPool на java.

Пример планировщика Java. Пример ScheduledExecutorService, Пример ScheduledThreadPoolExecutor, Исполнители Планировщик потоков newScheduledThreadPool на java.

Добро пожаловать в пример планировщика Java. Сегодня мы рассмотрим ScheduledExecutorService и его класс реализации ScheduledThreadPoolExecutor пример.

Планировщик Java ScheduledExecutorService

Иногда нам нужно выполнять задачу периодически или с определенной задержкой. Java предоставляет класс таймера, с помощью которого мы можем достичь этого, но иногда нам нужно выполнять аналогичные задачи параллельно. Таким образом, создание нескольких объектов таймера будет накладными расходами для системы, и лучше иметь пул потоков запланированных задач.

Java обеспечивает реализацию пула запланированных потоков через ScheduledThreadPoolExecutor класс, реализующий ScheduledExecutorService интерфейс. ScheduledExecutorService определяет методы контракта для планирования задачи с различными параметрами.

Некоторое время назад я написал сообщение о Java ThreadPoolExecutor , где я использовал класс Executors для создания пула потоков. Класс Executors также предоставляет заводские методы для создания ScheduledThreadPoolExecutor , где мы можем указать количество потоков в пуле.

Пример планировщика Java

Допустим, у нас есть простой управляемый класс, как показано ниже.

Допустим, у нас есть простой управляемый класс, как показано ниже.

package com.journaldev.threads; import java.util.Date; public class WorkerThread implements Runnable < private String command; public WorkerThread(String s)< this.command=s; >@Override public void run() < System.out.println(Thread.currentThread().getName()+" Start. Time = "+new Date()); processCommand(); System.out.println(Thread.currentThread().getName()+" End. Time wp-block-codemirror-blocks-code-block code-block">«> public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)

Читайте также:  Writing classes in php

Ниже приведен пример нашей программы планировщика java, использующей реализацию ScheduledExecutorService и ScheduledThreadPoolExecutor .

package com.journaldev.threads; import java.util.Date; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class ScheduledThreadPool < public static void main(String[] args) throws InterruptedException < ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5); //schedule to run after sometime System.out.println("Current Time = "+new Date()); for(int i=0; i//add some delay to let some threads spawn by scheduler Thread.sleep(30000); scheduledThreadPool.shutdown(); while(!scheduledThreadPool.isTerminated()) < //wait for all tasks to finish >System.out.println("Finished all threads"); > >

Когда мы запускаем приведенный выше пример программы планировщика java, мы получаем следующий вывод, подтверждающий, что задачи выполняются с задержкой в 10 секунд.

Current Time = Tue Oct 29 15:10:03 IST 2013 pool-1-thread-1 Start. Time = Tue Oct 29 15:10:14 IST 2013 pool-1-thread-2 Start. Time = Tue Oct 29 15:10:15 IST 2013 pool-1-thread-3 Start. Time = Tue Oct 29 15:10:16 IST 2013 pool-1-thread-1 End. Time = Tue Oct 29 15:10:19 IST 2013 pool-1-thread-2 End. Time = Tue Oct 29 15:10:20 IST 2013 pool-1-thread-3 End. Time = Tue Oct 29 15:10:21 IST 2013 Finished all threads

Обратите внимание, что все методы schedule() возвращают экземпляр Запланированное будущее , который мы можем использовать для получения информации о состоянии потока и времени задержки потока.

ScheduledFuture расширяет интерфейс будущего, подробнее о них читайте в примере вызываемого будущего Java .

В ScheduledExecutorService есть еще два метода, которые предоставляют возможность запланировать периодическое выполнение задачи.

ScheduledExecutorService scheduleAtFixedRate(выполняемая команда,длительный начальный срок,длительный период,единица измерения времени)

Мы можем использовать метод ScheduledExecutorService scheduleAtFixedRate для планирования выполнения задачи после начальной задержки, а затем с заданным периодом.

Период времени начинается с начала первого потока в пуле, поэтому, если вы указываете период в 1 секунду, а ваш поток выполняется в течение 5 секунд, следующий поток начнет выполняться, как только первый рабочий поток завершит свое выполнение.

Например, если у нас есть такой код:

Затем мы получим результат, как показано ниже.

Current Time = Tue Oct 29 16:10:00 IST 2013 pool-1-thread-1 Start. Time = Tue Oct 29 16:10:01 IST 2013 pool-1-thread-2 Start. Time = Tue Oct 29 16:10:02 IST 2013 pool-1-thread-3 Start. Time = Tue Oct 29 16:10:03 IST 2013 pool-1-thread-1 End. Time = Tue Oct 29 16:10:06 IST 2013 pool-1-thread-2 End. Time = Tue Oct 29 16:10:07 IST 2013 pool-1-thread-3 End. Time = Tue Oct 29 16:10:08 IST 2013 pool-1-thread-1 Start. Time = Tue Oct 29 16:10:11 IST 2013 pool-1-thread-4 Start. Time = Tue Oct 29 16:10:12 IST 2013

ScheduledExecutorService scheduleWithFixedDelay(выполняемая команда,длительное начальное время,длительная задержка,единица измерения времени)

ScheduledExecutorService scheduleWithFixedDelay Метод может использоваться для запуска периодического выполнения с начальной задержкой, а затем выполнения с заданной задержкой. Время задержки начинается с момента завершения выполнения потока. Итак, если у нас есть код, как показано ниже:

Затем мы получим результат, как показано ниже.

Current Time = Tue Oct 29 16:14:13 IST 2013 pool-1-thread-1 Start. Time = Tue Oct 29 16:14:14 IST 2013 pool-1-thread-2 Start. Time = Tue Oct 29 16:14:15 IST 2013 pool-1-thread-3 Start. Time = Tue Oct 29 16:14:16 IST 2013 pool-1-thread-1 End. Time = Tue Oct 29 16:14:19 IST 2013 pool-1-thread-2 End. Time = Tue Oct 29 16:14:20 IST 2013 pool-1-thread-1 Start. Time = Tue Oct 29 16:14:20 IST 2013 pool-1-thread-3 End. Time = Tue Oct 29 16:14:21 IST 2013 pool-1-thread-4 Start. Time = Tue Oct 29 16:14:21 IST 2013

Это все для примера планировщика java. Мы также узнали о потоке ScheduledExecutorService и ScheduledThreadPoolExecutor. Вам следует ознакомиться с другими статьями о многопоточности в Java .

Источник

Java — Scheduled Thread Pools

Scheduled executors are based on the interface ScheduledExecutorService which extends ExecutorService interface.

ScheduledExecutorService supports delayed and periodic execution of one or more submitted tasks, whereas ExecutorService supports just one time task execution of one or more submitted tasks.

ScheduledExecutorService is a convenient alternative to java.util.Timer for scheduling the tasks execution , just like ExecutorService is a convenient alternative to java.lang.Thread.

ScheduledExecutorService introduces new methods to create tasks with delays and periodicity properties.

Note that ScheduledExecutorService#scheduledWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) has different meanings than Timer#Schedule(TimerTask task, long delay, long period) , even though both are termed as fixed-delayed tasks in the API docs. The former meanings of delay refers to a fixed delay which separates every two tasks, whereas the latter (please explore details here ) refers to rather fixed-delay frequency where delay always starts at the begging of each task executions rather than at the end.

The ScheduledFuture interface

All methods in ScheduledExecutorService interface return ScheduledFuture . This interface extends Future , Delayed and Comparable interfaces.

Future interface is mainly used to get the results of a Callable results.

Delayed interface is used to indicate that this object supports some sort of delayed period.

ScheduledExecutorService doesn’t define any new method of its own.

The ScheduledThreadPoolExecutor class

This class extends ThreadPoolExecutor and implements ScheduledFuture.

This implementation can run multiple submitted tasks in parallel (the pool concept). If we compare this to java.util.Timer, one Timer instance uses only one thread even if multiple tasks are submitted. So basically all multiple tasks, we submit to a Timer instance, run in sequence to each other but over all execution run in a new thread. ScheduledThreadPoolExecutor can run multiple tasks periodically in parallel depending on the pool size.

Let’s explore ScheduledThreadPoolExecutor constructors quickly:

ScheduledThreadPoolExecutor(int corePoolSize, RejectedExecutionHandler handler)

ScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory)

ScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory, RejectedExecutionHandler handler)

Comparing with the constructors of the super class ThreadPoolExecutor (which we explored here ), there’s no new properties provided at the construction time. Also it doesn’t provide most of the super class construction time parameters. Most importantly it doesn’t provide a way to specify construction time BlockingQueue workQueue option like its super class. The reason is: this pool implementation uses only unbounded queue. According to ScheduledThreadPoolExecutor docs :

While this class inherits from ThreadPoolExecutor, a few of the inherited tuning methods are not useful for it. In particular, because it acts as a fixed-sized pool using corePoolSize threads and an unbounded queue, adjustments to maximumPoolSize have no useful effect. Additionally, it is almost never a good idea to set corePoolSize to zero or use allowCoreThreadTimeOut because this may leave the pool without threads to handle tasks once they become eligible to run.

Example Project

This example project includes scenarios where a single task or multiple tasks are submitted to the ScheduledThreadPoolExecutor instance having pool size one or two.

Dependencies and Technologies Used:

Источник

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