作用

将定时任务和线程池功能结合起来

使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class ScheduledThreadPoolExecutoreDemo1 {

public static void main(String[] args) {
List<Callable> callableList = new ArrayList<>();
callableList.add(new MyCallableA());
callableList.add(new MyCallableB());
// 使用的是单任务的计划任务池
ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
ScheduledFuture futureA = scheduledExecutorService.schedule(callableList.get(0), 4, TimeUnit.SECONDS);
ScheduledFuture futureB = scheduledExecutorService.schedule(callableList.get(1), 4, TimeUnit.SECONDS);
try {
System.out.println("Begin: " + System.currentTimeMillis());
System.out.println("futureA: " + futureA.get());
System.out.println("futureB: " + futureB.get());
System.out.println("End: " + System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}

static class MyCallableA implements Callable {
@Override
public Object call() throws Exception {
return "return A";
}
}

static class MyCallableB implements Callable {
@Override
public Object call() throws Exception {
return "return B";
}
}

}

上面示例的作用是延迟4秒后执行任务;schedule方法中的第一个参数也可以接收runnable类型的参数

  • scheduleAtFixedRate:周期性执行任务:

    1
    2
    ScheduledFuture<?> scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(new MyRunnable(), 1, 2, TimeUnit.SECONDS);
    System.out.println(scheduledFuture.get());

    需要注意的是该方法获取的scheduledFuture对象是无法获取到返回值的。

  • scheduleWithFixedDelay:该方法也是周期性执行任务

  • getQueue:获取队列中的任务,该队列中存放的是将要执行的任务

    1
    2
    ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(10);
    scheduledThreadPoolExecutor.getQueue();
  • remove:在队列中移除指定的任务

    1
    ScheduledThreadPoolExecutor.remove
  • setExecuteExistingDelayedTasksAfterShutdownPolicy:默认值为true,作用是当执行了shutdown方法后,判断任务是否继续执行,true则继续执行

  • setContinueExistingPeriodicTasksAfterShutdownPolicy:当为true时,使用scheduleWithFixedDelayscheduleAtFixedRate,如果执行了shutdown方法,则任务还会继续执行

  • cancel:是否取消任务,但是该任务依然会存在队列中,只是任务不会被执行

  • setRemoveOnCancelPolicy:是否将取消的任务从队列中清除