周期执行:scheduleAtFixedRate()
方法功能:
scheduleAtFixedRate(command, 2, 4, second):
第一次执行后延迟2秒后 执行第二次,然后每隔4秒执行一次,
如果执行耗时大于等待时间,那么将会在任务执行完成后立马开始执行下一轮任务。
如果执行耗时小于等待时间,那么将会在任务执行完成后等待【等待时间-执行耗时】,然后再执行下一轮任务
ScheduledExecutorService newScheduledThreadPool = Executors.newScheduledThreadPool(1);//创建固定大小 线程数 支持定时和周期性任务
ThreadPoolExecutorDemo1 poolExecutorDemo1=new ThreadPoolExecutorDemo1(1);
//第一次执行后延迟2秒后 执行第二次,然后每隔4秒执行一次
newScheduledThreadPool.scheduleAtFixedRate(poolExecutorDemo1, 2, 4, TimeUnit.SECONDS);
newScheduledThreadPool.submit(poolExecutorDemo1);
结果
线程池中正在运行的线程:2022-07-10 09:21:51
线程池中运行的线程结束:2022-07-10 09:21:52
线程池中正在运行的线程:2022-07-10 09:21:53
线程池中运行的线程结束:2022-07-10 09:21:54
线程池中正在运行的线程:2022-07-10 09:21:57
线程池中运行的线程结束:2022-07-10 09:21:58
线程池中正在运行的线程:2022-07-10 09:22:01
线程池中运行的线程结束:2022-07-10 09:22:02
线程池中正在运行的线程:2022-07-10 09:22:05
线程池中运行的线程结束:2022-07-10 09:22:06
周期执行:scheduleWithFixedDelay()
方法功能:
newScheduledThreadPool.scheduleWithFixedDelay(poolExecutorDemo1, 5, 4, TimeUnit.SECONDS);
第一次运行5秒后,开始运行第二次,在第二次结束后 等待4秒,运行第3次,以此类推。这是从第二次开始,在上次运行结束后等待4秒,开始运行下一次。
ScheduledExecutorService newScheduledThreadPool = Executors.newScheduledThreadPool(1);//创建固定大小 线程数 支持定时和周期性任务
ThreadPoolExecutorDemo1 poolExecutorDemo1=new ThreadPoolExecutorDemo1(1);
newScheduledThreadPool.scheduleWithFixedDelay(poolExecutorDemo1, 5, 4, TimeUnit.SECONDS);
newScheduledThreadPool.submit(poolExecutorDemo1);
结果
线程池中正在运行的线程:2022-07-10 10:13:56
线程池中运行的线程结束:2022-07-10 10:13:57
线程池中正在运行的线程:2022-07-10 10:14:01
线程池中运行的线程结束:2022-07-10 10:14:02
线程池中正在运行的线程:2022-07-10 10:14:06
线程池中运行的线程结束:2022-07-10 10:14:07
线程池中正在运行的线程:2022-07-10 10:14:11
线程池中运行的线程结束:2022-07-10 10:14:12
线程池中正在运行的线程:2022-07-10 10:14:16
线程池中运行的线程结束:2022-07-10 10:14:17
延迟执行并返回结果:schedule()
newScheduledThreadPool.schedule(poolExecutorDemo1, 5, TimeUnit.SECONDS);
在5秒后 执行第二次,执行还可以有返回值
ScheduledExecutorService newScheduledThreadPool = Executors.newScheduledThreadPool(1);//创建固定大小 线程数 支持定时和周期性任务
ThreadPoolExecutorDemo1 poolExecutorDemo1=new ThreadPoolExecutorDemo1(1);
newScheduledThreadPool.schedule(poolExecutorDemo1, 5, TimeUnit.SECONDS);
Future<?> submit = newScheduledThreadPool.submit(poolExecutorDemo1);
newScheduledThreadPool.shutdown();
线程池中正在运行的线程:2022-07-10 10:25:36
线程池中运行的线程结束:2022-07-10 10:25:37
线程池中正在运行的线程:2022-07-10 10:25:41
线程池中运行的线程结束:2022-07-10 10:25:42