您可以使用 来执行此操作ScheduledThreadPoolExecutor
,您可以使用它来实现任务的并行执行。一个安排任务的小示例:
//creates a thread pool of size 2
int poolSize = 2;
// creates ScheduledThreadPoolExecutor object with number of thread 2
ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(poolSize);
//starts executing after 1 second
ScheduledFuture<Callable-Type> sf = stpe.schedule(new TaskOne(), 1,TimeUnit.SECONDS);
//starts executing after 2 seconds
ScheduledFuture<Callable-Type> sf1 = stpe.schedule(new TaskTwo(), 2,TimeUnit.SECONDS);
你可以定义你的任务如下:
class TaskOne implements Callable<Callable-Type> {
@Override
public Callable-Type call() throws Exception {
//DO YOUR WORK HERE
return callable-type;
}
}
class TaskTwo implements Callable<Callable-Type> {
@Override
public Callable-Type call() throws Exception {
//DO YOUR WORK HERE
return callable-type;
}
}
使用ScheduledThreadPoolExecutor
over的优点Timer
是:
- Timer 只创建一个线程来执行定时器任务。计划线程池通过允许您提供多个线程来执行延迟和定期任务来解决此限制。
- Timer 的另一个问题是,如果 TimerTask 抛出未经检查的异常,它的行为就会很差。Timer 线程不会捕获异常,因此从 TimerTask 抛出的未经检查的异常会终止计时器线程。
参考:Java 并发实践