Java Multithreading ~~~ Use of ScheduledThreadPoolExecutor to schedule tasks
We have learned how to use the ThreadPoolExecutor class to automatically create and run threads. But those threads run as soon as they are submitted.
We sometimes want to run a task without submitting it, but delay for a period of time or periodically. What should we do?
ScheduledThreadPoolExecutor can help us achieve this effect. The Code is as follows.
package com.bird.concursey.charpet7;import java.util.Date;import java.util.concurrent.Callable;import java.util.concurrent.Executors;import java.util.concurrent.ScheduledThreadPoolExecutor;import java.util.concurrent.TimeUnit;public class Task implements Callable
{private String name;public Task(String name) {super();this.name = name;}@Overridepublic String call() throws Exception {System.out.printf("%s: Starting at : %s\n",name,new Date());return "hello world";}public static void main(String[] args) {ScheduledThreadPoolExecutor executor = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1);System.out.printf("Main: Starting at: %s\n",new Date());for(int i = 0; i < 5; i++) {Task task = new Task("Task " + i);executor.schedule(task, i, TimeUnit.SECONDS);}executor.shutdown();try {executor.awaitTermination(1, TimeUnit.DAYS);} catch (InterruptedException e) {e.printStackTrace();}System.out.printf("Main: Ends at: %s\n",new Date());}}
The running result is displayed.
Main: Starting at: Fri Sep 26 21:59:50 CST 2014Task 0: Starting at : Fri Sep 26 21:59:50 CST 2014Task 1: Starting at : Fri Sep 26 21:59:51 CST 2014Task 2: Starting at : Fri Sep 26 21:59:52 CST 2014Task 3: Starting at : Fri Sep 26 21:59:53 CST 2014Task 4: Starting at : Fri Sep 26 21:59:54 CST 2014Main: Ends at: Fri Sep 26 21:59:54 CST 2014
Although all tasks are submitted at the same time, dan 'shi