ScheduledExecutorService with Runnable

Category : Java | Sub Category : ExecutorService | By Runner Dev Last updated: 2020-11-30 15:50:04 Viewed : 175


 

1. ScheduledExecutorService with Runnable
     java.util.concurrent.Executors.newScheduledThreadPool(int corePoolSize)

 

Creates a thread pool that can schedule commands to run after a given delay, or to execute periodically.

Parameters:

corePoolSize the number of threads to keep in the pool, even if they are idle

Returns:

a newly created scheduled thread pool

Throws:

IllegalArgumentException - if corePoolSize < 0

2.  Example:

ScheduledExecutorRunnable.java

 

package runnerdev;

 

import java.util.concurrent.Executors;

import java.util.concurrent.ScheduledExecutorService;

import java.util.concurrent.TimeUnit;

 

public class ScheduledExecutorRunnable {

 

     public static void main(String[] args) {

 

         ScheduledExecutorService ses = Executors.newScheduledThreadPool(1);

 

         Runnable task1 = () -> System.out.println("Service Running task 1");

 

         task2();

 

         // run this task after 5 seconds

         ses.schedule(task1, 5, TimeUnit.SECONDS);

 

         task3();

 

         ses.shutdown();

 

     }

 

     public static void task2() {

         System.out.println(" Service Running task 2 ");

     }

 

     public static void task3() {

         System.out.println("ServiceRunning task 3 ");

     }

 

} 


Output:

Service Running task 2

ServiceRunning task 3

Service Running task 1

Search
Related Articles

Leave a Comment: