Follow these steps to implement the example:
- Create a class named Task that implements the Callable interface parameterized by the String class:
public class Task implements Callable<String> {
- Declare a private String attribute called name that will store the name of the task:
private final String name;
- Implement the constructor of the class that initializes the name attribute:
public Task(String name) {
this.name=name;
}
- 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";
}
- 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) {
- 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);
- 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);
}
- Request the finalization of the executor using the shutdown() method:
executor.shutdown();
- 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();
}
- Write a message to indicate the time when the program will finish:
System.out.printf("Main: Ends at: %s ",new Date());