1、ScheduledThreadPool简介
ScheduledThreadPool
是核心线程数量固定,非核心线程数量无限,执行完闲置 10ms 后回收,任务队列为延时阻塞队列。一般是用在执行定时或周期性任务的使用场景。相对于通过使用 ThreadPoolExecutor
的方式,使用ScheduledThreadPool
更方便,有些参数可能不需要设置,可以根据实现情况使用。
2、newFixedThreadPool源码
private static final long DEFAULT_KEEPALIVE_MILLIS = 10L;
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE,
DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
new DelayedWorkQueue());
}
public static ScheduledExecutorService newScheduledThreadPool(
int corePoolSize, ThreadFactory threadFactory) {
return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
}
public ScheduledThreadPoolExecutor(int corePoolSize,
ThreadFactory threadFactory) {
super(corePoolSize, Integer.MAX_VALUE,
DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
new DelayedWorkQueue(), threadFactory);
}
3、使用示例
import java.util.concurrent.*;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class Main {
public static void main(String[] args) throws Exception {
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
// 需执行的任务
Runnable task =new Runnable(){
public void run() {
Date date=new Date();
DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(" 当前时间为:"+dateFormat.format(date));
}
};
//添加任务
scheduledThreadPool.schedule(task, 1, TimeUnit.SECONDS); // 延迟1s后执行任务
scheduledThreadPool.scheduleAtFixedRate(task,10,1000,TimeUnit.MILLISECONDS);// 延迟10ms后、每隔1000ms执行任务
scheduledThreadPool.awaitTermination(10000, TimeUnit.MILLISECONDS);
System.exit(0); //success
}
}