ScheduledExecutorService with Callable

Category : Java | Sub Category : ExecutorService | By Prasad Bonam Last updated: 2020-11-30 10:21:25 Viewed : 582


1. ScheduledExecutorService with Callable
<IntegerScheduledFuture<Integerjava.util.concurrent.ScheduledExecutorService.schedule(Callable<Integer> callable, long delay, TimeUnit unit)
 Creates and executes a ScheduledFuture that becomes enabled after the given delay.

2.  Example:

ScheduledExecutorCallable.java

 import java.util.concurrent.*;

 

public class ScheduledExecutorCallable {

 

     public static void main(String[] args) throws InterruptedException, ExecutionException {

 

         ScheduledExecutorService ses = Executors.newScheduledThreadPool(1);

 

         Callable<Integer> task2 = () -> 111;

 

         task1();

 

         // run this task after 5 seconds

         ScheduledFuture<Integer> schedule = ses.schedule(task2, 5, TimeUnit.SECONDS);

 

         task3();

 

         // block and get the result

         System.out.println(schedule.get());

 

         System.out.println("shutdown!");

 

         ses.shutdown();

 

     }

 

     public static void task1() {

         System.out.println("Running task 1 ");

     }

 

     public static void task3() {

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

     }

 

}

 Output:

Running task 1

Running task 3

111

shutdown!

Search
Related Articles

Leave a Comment: