demo:
public class ScheduledThreadPoolExecutorSample {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//初始延迟执行线程池
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
System.out.println("1.start" + ",time:" + LocalDateTime.now().format(timeFormatter));
ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(1);
//普通的延迟执行
scheduledThreadPoolExecutor.schedule(()->{
System.out.println("延迟5秒执行。。。" + ",time:" + LocalDateTime.now().format(timeFormatter));
},5000, TimeUnit.MILLISECONDS);
//这里可以写主线程的业务,这里不会阻塞去等上面的延迟执行
System.out.println("2.这里可以写主线程的业务,这里不会阻塞去等上面的5秒延迟执行" + ",time:" + LocalDateTime.now().format(timeFormatter));
//也可以在延迟执行块里做一些逻辑任务,做完任务处理后并返回一个任务处理的结果值
ScheduledFuture<Integer> future = scheduledThreadPoolExecutor.schedule(()->{
System.out.println("延迟10秒执行。。。" + ",time:" + LocalDateTime.now().format(timeFormatter));
return 1;
},10000, TimeUnit.MILLISECONDS);
//这里可以写主线程的业务,这里不会阻塞去等上面的延迟执行
System.out.println("3.这里也可以写主线程的业务,这里不会阻塞去等上面的10延迟执行" + ",time:" + LocalDateTime.now().format(timeFormatter));
//future.get()会阻塞线程,会在这里等结果再继续往下执行
System.out.println("4.这里会阻塞等待future执行完返回结果再往下" + ",time:" + LocalDateTime.now().format(timeFormatter));
System.out.println("5.future.get()执行任务返回结果值:"+future.get() + ",time:" + LocalDateTime.now().format(timeFormatter));
//周期性执行,如发送心跳,scheduleAtFixedRate是每间隔3秒就开始执行任务,并不管任务里是否已经完成了的,如果任务超过3秒才完成那就会堆积任务。
scheduledThreadPoolExecutor.scheduleAtFixedRate(()->{
System.out.println("周期性执行任务。。。" + ",time:" + LocalDateTime.now().format(timeFormatter));
},5000,3000,TimeUnit.MILLISECONDS);
System.out.println("6.这里也可以写主线程的业务,这里不会阻塞去等上面的周期性执行任务" + ",time:" + LocalDateTime.now().format(timeFormatter));
//周期性执行,scheduleWithFixedDelay和scheduleAtFixedRate不同,scheduleWithFixedDelay是等任务执行完再间隔3秒才开始下一个任务
scheduledThreadPoolExecutor.scheduleWithFixedDelay(()->{
System.out.println("完成周期性任务间隔3秒后再继续执行新的周期性任务。。。" + ",time:" + LocalDateTime.now().format(timeFormatter));
},5000,3000,TimeUnit.MILLISECONDS);
System.out.println("7.这里也可以写主线程的业务,这里不会阻塞去等上面的周期性执行任务" + ",time:" + LocalDateTime.now().format(timeFormatter));
System.out.println("8.end" + ",time:" + LocalDateTime.now().format(timeFormatter));
}
}