4.5指定一段时间运行并发任务
当你发送一个任务给指定的executor时,它依据executor的配置来迅速被运行。当你对线程的运行不太感兴趣,只需要它快速的运行就可以了,这就是它的使用场合。当你想间歇地执行一个任务或者定期地执行一个任务。对于这些目的,Executor框架提供了一个ScheduledThreadPoolExecutor类。请看下面实例实例代码。
定义Task类,实现一个简单的逻辑。
import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
importjava.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* This class implements the task ofthis example. Writes a
* message to the console with theactual date and returns the
* 'Hello, world' string
*
*/
public class Task implements Callable<String> {
/**
* Name of the task
*/
private Stringname;
/**
* Constructor of the class
* @param name Name of the task
*/
public Task(String name) {
this.name=name;
}
/**
* Main method of the task. Writes a message tothe console with
* the actual date and returns the 'Helloworld' string
*/
@Override
public String call()throws Exception {
System.out.printf("%s: Starting at : %s\n",name,new Date());
return"Hello, world";
}
/**
* Main method of the example
* @param args
*/
public staticvoidmain(String[] args) {
// Create a ScheduledThreadPoolExecutor
ScheduledExecutorService executor=(ScheduledExecutorService)Executors.newScheduledThreadPool(1);
System.out.printf("Main: Starting at: %s\n",new Date());
// Send the tasks to the executor with the specified delay
for (int i=0; i<5; i++) {
Task task=new Task("Task "+i);
executor.schedule(task,i+1 ,TimeUnit.SECONDS);
}
// Finish the executor
executor.shutdown();
// Waits for the finalization of the executor
try {
executor.awaitTermination(1,TimeUnit.DAYS);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Writes the finalization message
System.out.printf("Core: Ends at: %s\n",new Date());
}
}
运行结果:
Main:Starting at: Sun Mar 30 23:03:12 CST 2014
Task0: Starting at : Sun Mar 30 23:03:13 CST 2014
Task1: Starting at : Sun Mar 30 23:03:14 CST 2014
Task2: Starting at : Sun Mar 30 23:03:15 CST 2014
Task3: Starting at : Sun Mar 30 23:03:16 CST 2014
Task4: Starting at : Sun Mar 30 23:03:17 CST 2014
Core:Ends at: Sun Mar 30 23:03:17 CST 2014