How to do it...

Follow these steps to implement the example:

  1. Create a class named Task that implements the Callable interface parameterized by the String class:
        public class Task implements Callable<String> {
  1. Declare a private String attribute called name that will store the name of the task:
        private final String name;
  1. Implement the constructor of the class that initializes the name attribute:
        public Task(String name) { 
this.name=name;
}
  1. Implement the call() method. Write a message to the console with the actual date and return some text, for example, Hello, world:
        public String call() throws Exception { 
System.out.printf("%s: Starting at : %s ",name,new Date());
return "Hello, world";
}
  1. Implement the main class of the example by creating a class named Main and adding the main() method to it:
        public class Main { 
public static void main(String[] args) {
  1. Create an executor of the ScheduledThreadPoolExecutor class using the newScheduledThreadPool() method of the Executors class, passing 1 as a parameter:
        ScheduledExecutorService executor=Executors
.newScheduledThreadPool(1);
  1. Initialize and start a few tasks (five in our case) with the schedule() method of the ScheduledThreadPoolExecutor instance:
        System.out.printf("Main: Starting at: %s
",new Date()); 
for (int i=0; i<5; i++) {
Task task=new Task("Task "+i);
executor.schedule(task,i+1 , TimeUnit.SECONDS);
}
  1. Request the finalization of the executor using the shutdown() method:
        executor.shutdown();
  1. Wait for the finalization of all the tasks using the awaitTermination() method of the executor:
        try { 
executor.awaitTermination(1, TimeUnit.DAYS);
} catch (InterruptedException e) {
e.printStackTrace();
}
  1. Write a message to indicate the time when the program will finish:
        System.out.printf("Main: Ends at: %s
",new Date());
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.31.163