0
java | ScheduledThreadPoolExecutor 使用
source link: https://benpaodewoniu.github.io/2023/01/02/java164/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
任务调度线程池。
Timer 缺点
在「任务调度线程池」功能加入之前,可以使用 java.util.Timer 来实现定时功能,Timer 的有点在于简单。
但是,由于所有任务都是由一个线程来调度,因此,所有的任务都是串行执行的,同一时间只能有一个任务在执行,前一个任务的延迟或异常都将会影响到之后的任务。
package com.redisc;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import java.util.*;
import java.util.concurrent.*;
@Slf4j(topic = "c.Test")
public class Run {
public static void main(String[] args) throws InterruptedException, ExecutionException {
Timer timer = new Timer();
TimerTask task1 = new TimerTask() {
@SneakyThrows
@Override
public void run() {
log.debug("task1");
Thread.sleep(2000);
}
};
TimerTask task2 = new TimerTask() {
@Override
public void run() {
log.debug("task2");
}
};
log.debug("start...");
timer.schedule(task1,1000);
timer.schedule(task2,1000);
}
}
期望两个任务都是 1
秒后执行,但是,实际输出
22:56:02.714 [main] DEBUG c.Test - start...
22:56:03.719 [Timer-0] DEBUG c.Test - task1
22:56:05.723 [Timer-0] DEBUG c.Test - task2
如果 task1
有异常,那么,task2
不会执行。
ScheduledThreadPoolExecutor
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK