并发编程(七):线程池、ThreadPoolExecutor、任务调度线程池
一、线程池
1.为什么需要线程池
我们已经可以通过创建多线程来提高并发,为什么还需要线程池?
- 降低资源消耗。通过重复利用已创建的线程降低线程创建和销毁造成的消耗。(创建的线程,实际最后要和操作系统的线程做映射,很消耗资源)
- 提高响应速度。当任务到达时,任务可以不需要等到线程创建就能立即执行。
- 提高线程的可管理性。线程是稀缺资源,如果无限制的创建,不仅会消耗系统资源,还会降低系统的稳定性,使用线程池可以进行统一的分配,调优和监控。
2.自定义线程池
- 阻塞队列中维护了由主线程(或者其他线程)所产生的的任务
- 主线程类似于生产者,产生任务并放入阻塞队列中
- 线程池类似于消费者,得到阻塞队列中已有的任务并执行
(1)自定义阻塞队列
//自定义阻塞队列
/**
* 用于存放任务的阻塞队列
*
* @param <T> Runnable, 任务抽象为Runnable
*/
@Slf4j
class BlockingQueue<T> {
// 1、任务队列
private Deque<T> queue = new ArrayDeque<>();
// 2、锁
private ReentrantLock lock = new ReentrantLock();
// 3、生产者的条件变量 (当阻塞队列塞满任务的时候, 没有空间, 此时进入条件变量中等待)
private Condition fullWaitSet = lock.newCondition();
// 4、消费者的条件变量 (当没有任务可以消费的时候, 进入条件变量中等待)
private Condition emptyWaitSet = lock.newCondition();
// 5、阻塞队列的容量
private int capacity;
public BlockingQueue(int capacity) {
this.capacity = capacity;
}
// take:从阻塞队列中获取任务, 如果没有任务,会一直等待
public T take() {
lock.lock();
try {
// 阻塞队列是否为空
while (queue.isEmpty()) {
// 进入消费者的条件变量中等待,此时没有任务供消费
try {
emptyWaitSet.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 阻塞队列不为空, 获取队列头部任务
T t = queue.removeFirst();
fullWaitSet.signal(); // 唤醒生产者进行生产, 此时阻塞队列没有满
return t;
} finally {
lock.unlock();
}
}
// put:往阻塞队列中添加任务
public void put(T task) {
lock.lock();
try {
// 阻塞队列是否满了
while (queue.size() == capacity) {
try {
log.debug("等待进入阻塞队列...");
fullWaitSet.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
queue.addLast(task);
log.debug("加入任务阻塞队列 {}", task);
emptyWaitSet.signal(); // 此时阻塞队列中有任务了, 唤醒消费者进行消费任务
} finally {
lock.unlock();
}
}
// poll:从阻塞队列中获取任务, 如果没有任务, 会等待指定的时间
public T poll(long timeout, TimeUnit unit) {
lock.lock();
try {
// 将timeout统一转换为纳秒
long nanos = unit.toNanos(timeout);
while (queue.isEmpty()) {
try {
// 表示超时, 无需等待, 直接返回null
if (nanos <= 0) {
return null;
}
// 返回值的时间(剩余时间) = 等待时间 - 经过时间 所以不存在虚假唤醒(时间还没等够就被唤醒,然后又从新等待相同时间)
nanos = emptyWaitSet.awaitNanos(nanos);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
T t = queue.removeFirst();
fullWaitSet.signal(); // 唤醒生产者进行生产, 此时阻塞队列没有满
return t;
} finally {
lock.unlock();
}
}
// offer:往阻塞队列中添加任务(带超时)
public boolean offer(T task, long timeout, TimeUnit timeUnit) {
lock.lock();
try {
long nanos = timeUnit.toNanos(timeout);
while (queue.size() == capacity) {
try {
if (nanos <= 0) {
return false;
}
log.debug("等待进入阻塞队列 {}...", task);
nanos = fullWaitSet.awaitNanos(nanos);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
log.debug("加入任务阻塞队列 {}", task);
queue.addLast(task);
emptyWaitSet.signal(); // 此时阻塞队列中有任务了, 唤醒消费者进行消费任务
return true;
} finally {
lock.unlock();
}
}
//tryput: 加入了拒绝策略
public void tryPut(RejectPolicy<T> rejectPolicy, T task) {
lock.lock();
try {
// 判断队列是否满
if (queue.size() == capacity) {
rejectPolicy.reject(this, task);
} else {
// 有空闲
log.debug("加入任务队列 {}", task);
queue.addLast(task);
emptyWaitSet.signal();
}
} finally {
lock.unlock();
}
}
// 获取队列大小
public int size() {
lock.lock();
try {
return queue.size();
} finally {
lock.unlock();
}
}
}
(2)自定义线程池
//自定义线程池
@Slf4j
class ThreadPool {
// 阻塞任务队列
private BlockingQueue<Runnable> taskQueue;
// 线程集合
private HashSet<Worker> workers = new HashSet<>();
// 核心线程数
private int coreSize;
// 获取任务的超时时间
private long timeout;
//时间单位
private TimeUnit timeUnit;
// 拒绝策略
private RejectPolicy<Runnable> rejectPolicy;
//构造方法
public ThreadPool(int coreSize, long timeout, TimeUnit timeUnit, int queueCapacity, RejectPolicy<Runnable> rejectPolicy) {
this.coreSize = coreSize;
this.timeout = timeout;
this.timeUnit = timeUnit;
this.taskQueue = new BlockingQueue<>(queueCapacity);
this.rejectPolicy = rejectPolicy;
}
// 执行任务
public void execute(Runnable task) {
synchronized (workers) {
// 当任务数没有超过 coreSize 时,直接交给 worker 对象执行
// 如果任务数超过 coreSize 时,执行拒绝策略
if (workers.size() < coreSize) {
Worker worker = new Worker(task);
log.debug("新增 worker {}, {}", worker, task);
workers.add(worker);
worker.start();
} else {
// taskQueue.put(task); // 这一种死等
// 拒绝策略
// 1、死等
// 2、带超时等待
// 3、让调用者放弃任务执行
// 4、让调用者抛弃异常
// 5、让调用者自己执行任务
taskQueue.tryPut(rejectPolicy, task);
}
}
}
class Worker extends Thread {
private Runnable task;
public Worker(Runnable task) {
this.task = task;
}
@Override
public void run() {
// 执行任务
// 1): 当task不为空, 执行任务
// 2): 当task执行完毕, 从阻塞队列中获取任务并执行
//while (task != null || (task = taskQueue.take()) != null) {
while (task != null || (task = taskQueue.poll(timeout, timeUnit)) != null) {
try {
log.debug("正在执行...{}", task);
task.run();
} catch (Exception e) {
e.printStackTrace();
} finally {
task = null;
}
}
// 将线程集合中的线程移除
synchronized (workers) {
log.debug("worker被移除 {}", this);
workers.remove(this);
}
}
}
}
(3)自定义拒绝策略
@Slf4j
public class TestPool {
public static void main(String[] args) {
ThreadPool threadPool = new ThreadPool(1, 1000, TimeUnit.MILLISECONDS, 1, new RejectPolicy<Runnable>() {
//将拒绝策略交给线程池实现,而不是由阻塞队列写死
@Override
public void reject(BlockingQueue<Runnable> queue, Runnable task) {
// 拒绝策略
// 1、死等
// queue.put(task);
// 2、带超时等待
queue.offer(task, 2000, TimeUnit.MILLISECONDS);
// 3、让调用者放弃任务执行
// log.debug("放弃-{}", task);
// 4、让调用者抛弃异常
// throw new RuntimeException("任务执行失败" + task);
// 5、让调用者自己执行任务
// task.run();
}
});
// 创建5个任务
for (int i = 0; i < 4; i++) {
int j = i;
threadPool.execute(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.debug("{}", j);
}
});
}
}
}
@FunctionalInterface
interface RejectPolicy<T> {
void reject(BlockingQueue<T> queue, T task);
}
二、ThreadPoolExecutor
1.继承关系
- 任务类 (Runnable /Callable)
执行任务需要实现的 Runnable 接口 或 Callable接口。Runnable 接口或 Callable 接口 实现类都可以被ThreadPoolExecutor 或 ScheduledThreadPoolExecutor 执行。
- 任务的执行 (Executor)
如上图所示,包括任务执行机制的核心接口 Executor ,以及继承自 Executor 接口的 ExecutorService> 接口。ThreadPoolExecutor 和 ScheduledThreadPoolExecutor 这两个关键类实现了> ExecutorService 接口。
- 异步计算的结果 (Future)
Future 接口 以及 Future接口的 实现类 FutureTask 类 都可以代表异步计算的结果。 当把 Runnable接口 或 Callable 接口 的实现类提交给 ThreadPoolExecutor 或 scheduledThreadPoolExecutor 执行。(调用 submit() 方法时会返回一个 FutureTask对象)
2.线程池状态
- ThreadPoolExecutor 使用 int 的高 3 位来表示线程池状态,低 29 位表示线程数量;
- 这些信息存储在一个原子变量 ctl 中,目的是将线程池状态与线程个数合二为一,这样就可以用一次 cas 原子操作进行赋值
// c 为旧值, ctlOf 返回结果为新值
ctl.compareAndSet(c, ctlOf(targetState, workerCountOf(c))));
// rs 为高 3 位代表线程池状态, wc 为低 29 位代表线程个数,ctl 是合并它们
private static int ctlOf(int rs, int wc) { return rs | wc; }
3.构造方法
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
- corePoolSize 核心线程数目 (最多保留的线程数)
- maximumPoolSize 最大线程数目
- keepAliveTime 生存时间 - 针对救急线程
maximumPoolSize - corePoolSize = 救急线程数
救急线程在没有空闲的核心线程和任务队列满了的情况才使用救急线程 - unit 时间单位 - 针对救急线程
- workQueue 阻塞队列
有界阻塞队列 ArrayBlockingQueue
无界阻塞队列 LinkedBlockingQueue
最多只有一个同步元素的 SynchronousQueue
优先队列 PriorityBlockingQueue - threadFactory 线程工厂 - 可以为线程创建时起个好名字
- handler 拒绝策略
拒绝策略:如果线程到达 maximumPoolSize 仍然有新任务这时会执行拒绝策略。拒绝策略 jdk 提供了 4 种实现
- AbortPolicy 中止策略:丢弃任务并抛出RejectedExecutionException异常。这是默认策略。
- DiscardPolicy 丢弃策略:丢弃任务,但是不抛出异常。如果线程队列已满,则后续提交的任务都会被丢弃,且是静默丢弃。
- DiscardOldestPolicy 弃老策略:丢弃队列最前面的任务,然后重新提交被拒绝的任务。
- CallerRunsPolicy 调用者运行策略:由调用线程处理该任务。
4.Executors类
根据构造方法,JDK Executors 类中提供了众多工厂方法来创建各种用途的线程池。
3.1 newFixedThreadPool
固定大小线程池,可以传入两个参数。
public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
//核心线程数和最大线程数一致,无救急线程,阻塞队列无界
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
threadFactory);
}
使用例子:自定义线程工厂、自定义任务、创建线程池、执行任务
public class TestFixedThreadPool {
public static void main(String[] args) {
// A.自定义线程工厂,自定义线程名称
ThreadFactory factory = new ThreadFactory() {
AtomicInteger atomicInteger = new AtomicInteger(1);
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "myThread_" + atomicInteger.getAndIncrement());
}
};
// B.自定义任务
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
System.out.println("this is fixedThreadPool");
}
};
// C.创建核心线程数(最大线程数)为2的线程池,通过 ThreadFactory给线程起名字
ExecutorService executorService = Executors.newFixedThreadPool(2, factory);
//D.执行任务
executorService.execute(runnable);
}
}
- 核心线程数 == 最大线程数(没有救急线程被创建),因此也无需超时时间
- 阻塞队列是无界的,可以放任意数量的任务
- 适用于任务量已知,相对耗时的任务
3.2 newCachedThreadPool
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
- 没有核心线程,最大线程数为Integer.MAX_VALUE,所有创建的线程都是救急线程 (可以无限创建),空闲时生存时间为60秒
- 阻塞队列使用的是SynchronousQueue,SynchronousQueue是一种特殊的队列没有容量,没有线程来取是放不进去的,只有当线程取任务时,才会将任务放入该阻塞队列中
- 整个线程池表现为线程数会根据任务量不断增长,没有上限,当任务执行完毕,空闲 1分钟后释放线程。
- 适合任务数比较密集,但每个任务执行时间较短的情况
3.3 newSingleThreadExecutor
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
希望多个任务排队执行。线程数固定为 1,任务数多于 1 时,会放入无界队列排队。 任务执行完毕,这唯一的线程也不会被释放。
和自己创建单线程执行任务的区别:
- 自己创建一个单线程串行执行任务,如果任务执行失败而终止那么没有任何补救措施,而newSingleThreadExecutor线程池还会新建一个线程,保证池的正常工作
- Executors.newSingleThreadExecutor() 线程个数始终为1,不能修改
FinalizableDelegatedExecutorService 应用的是装饰器模式,只对外暴露了 ExecutorService 接口,因此不能调用 ThreadPoolExecutor 中特有的方法
和Executors.newFixedThreadPool(1) 初始时为1时的区别:
- Executors.newFixedThreadPool(1) 初始时为1,以后还可以修改,对外暴露的是 ThreadPoolExecutor 对象,可以强转后调用 setCorePoolSize 等方法进行修改
5.EOS 禁用 Executors原因
EOS建议使用ThreadPoolExecutor来创建线程池(使用有界队列,控制线程创建数量),使用Executors 返回线程池对象的弊端如下:
-
FixedThreadPool 和 SingleThreadExecutor : 允许请求的队列长度为 Integer.MAX_VALUE (无界阻塞队列),可能堆积大量的请求,从而导致 OOM。
-
CachedThreadPool 和 ScheduledThreadPool : 允许创建的线程数量为 Integer.MAX_VALUE ,可能会创建大量线程,从而导致 OOM。
-
实际使用中需要根据自己机器的性能、业务场景来手动配置线程池的参数比如核心线程数、使用的任务队列、饱和策略等等。
-
我们应该显示地给我们的线程池命名,这样有助于我们定位问题。
6.提交任务
// 执行任务
void execute(Runnable command);
// 提交任务 task,用返回值 Future 获得任务执行结果
<T> Future<T> submit(Callable<T> task);
// 提交 tasks 中所有任务
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException;
// 提交 tasks 中所有任务,带超时时间
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException;
// 提交 tasks 中所有任务,哪个任务先成功执行完毕,返回此任务执行结果,其它任务取消
<T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException;
// 提交 tasks 中所有任务,哪个任务先成功执行完毕,返回此任务执行结果,其它任务取消,带超时时间
<T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;
举个例子:
// 通过submit执行Callable中的call方法
// 通过Future来捕获返回值
Future<String> future = threadPool.submit(new Callable<String>() {
@Override
public String call() throws Exception {
return "hello submit";
}
});
// 查看捕获的返回值
System.out.println(future.get());
7.线程池操作API
除了执行、提交任务之外,还有其它一些操作线程池的API,如下
void shutdown() 线程池状态变为 SHUTDOWN
- 不会接收新任务
- 但已提交任务会执行完
- 此方法不会阻塞调用线程的执行
//具体实现
public void shutdown() {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
checkShutdownAccess();
// 修改线程池状态
advanceRunState(SHUTDOWN);
// 仅会打断空闲线程
interruptIdleWorkers();
onShutdown(); // 扩展点 ScheduledThreadPoolExecutor
} finally {
mainLock.unlock();
}
// 尝试终结(没有运行的线程可以立刻终结,如果还有运行的线程也不会等)
tryTerminate();
}
shutdownNow() 将线程池的状态改为 STOP
- 不再接受新任务,也不会在执行阻塞队列中的任务
- 并用 interrupt 的方式中断正在执行的任务
- 会将阻塞队列中未执行的任务返回给调用者
public List<Runnable> shutdownNow() {
List<Runnable> tasks;
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
checkShutdownAccess();
// 修改状态为STOP,不执行任何任务
advanceRunState(STOP);
// 中断所有线程
interruptWorkers();
// 将未执行的任务从队列中移除,然后返回给调用者
tasks = drainQueue();
} finally {
mainLock.unlock();
}
// 尝试终结,一定会成功,因为阻塞队列为空了
tryTerminate();
return tasks;
}
其它方法
// 不在 RUNNING 状态的线程池,此方法就返回 true
boolean isShutdown();
// 线程池状态是否是 TERMINATED
boolean isTerminated();
// 调用 shutdown 后,由于调用使线程结束线程的方法是异步的并不会等待所有任务运行结束就返回,因此如果它想在线程池 TERMINATED 后做些其它事情,可以利用此方法等待
boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException;
三、异步模式:工作线程
1.定义
让有限的工作线程(Worker Thread)来轮流异步处理无限多的任务。也可以将其归类为分工模式,它的典型实现就是线程池,体现了设计模式中的享元模式。
- 例如,海底捞的服务员(线程),轮流处理每位客人的点餐(任务),如果为每位客人都配一名专属的服务员,那么成本就太高了。
- 但是,如果一个餐馆的工人既要招呼客人(任务类型A),又要到后厨做菜(任务类型B)显然效率不咋地,分成服务员(线程池A)与厨师(线程池B)更为合理。
2.饥饿
两个工人是同一个线程池中的两个线程,他们要做的事情是:为客人点餐和到后厨做菜。
客人点餐:必须先点完餐,等菜做好,上菜,在此期间处理点餐的工人必须等待
后厨做菜:做菜
比如工人A 处理了点餐任务,接下来它要等着 工人B 把菜做好,然后上菜,他俩也配合的挺好; 但现在同时来了两个客人,这个时候工人A 和工人B 都去处理点餐了,这时没人做饭了,饥饿。
3.解决方案
- 解决方法可以增加线程池的大小,不过不是根本解决方案;
- 不同的任务类型,采用不同的线程池,可以避免这种现象发生。
@Slf4j
public class TestStarvation {
static final List<String> MENU = Arrays.asList("地三鲜", "宫保鸡丁", "辣子鸡丁", "烤鸡翅");
static Random RANDOM = new Random();
static String cooking() {
return MENU.get(RANDOM.nextInt(MENU.size()));
}
public static void main(String[] args) {
ExecutorService waiterPool = Executors.newFixedThreadPool(1);
ExecutorService cookPool = Executors.newFixedThreadPool(1);
waiterPool.execute(() -> {
log.debug("处理点餐...");
Future<String> f = cookPool.submit(() -> {
log.debug("做菜");
return cooking();
});
try {
log.debug("上菜: {}", f.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
});
waiterPool.execute(() -> {
log.debug("处理点餐...");
Future<String> f = cookPool.submit(() -> {
log.debug("做菜");
return cooking();
});
try {
log.debug("上菜: {}", f.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
});
}
}
4. 预设线程池数量
过小会导致程序不能充分地利用系统资源、容易导致饥饿,过大会导致更多的线程上下文切换,占用更多内存.
CPU 密集型运算
- 通常采用 cpu 核数 + 1 能够实现最优的 CPU 利用率,+1 是保证当线程由于页缺失故障(操作系统)或其它原因导致暂停时,额外的这个线程就能顶上去,保证 CPU 时钟周期不被浪费
I/O 密集型运算
- CPU 不总是处于繁忙状态,例如,当你执行业务计算时,这时候会使用 CPU 资源,但当你执行 I/O 操作时、远程RPC 调用时,包括进行数据库操作时,这时候 CPU 就闲下来了,你可以利用多线程提高它的利用率。
经验公式如下: - 线程数 = 核数 * 期望 CPU 利用率 * 总时间(CPU计算时间+等待时间) / CPU 计算时间
例如 4 核 CPU 计算时间是 50% ,其它等待时间是 50%,期望 cpu 被 100% 利用,套用公式4 * 100% * 100% / 50% = 8
四、任务调度线程池
1.Timer介绍
在『任务调度线程池』功能加入之前,可以使用 java.util.Timer 来实现定时功能,Timer 的优点在于简单易用,但由于所有任务都是由同一个线程来调度,因此所有任务都是串行执行的,同一时间只能有一个任务在执行,前一个任务的延迟或异常都将会影响到之后的任务。
@Slf4j(topic = "x.TestTimer")
public class TestTimer {
public static void main(String[] args) {
Timer timer = new Timer();
TimerTask task1 = new TimerTask() {
@Override
public void run() {
log.debug("task 1");
Sleeper.sleep(2);
}
};
TimerTask task2 = new TimerTask() {
@Override
public void run() {
log.debug("task 2");
}
};
// 使用timer添加两个任务, 希望他们都在1s后执行
// 由于timer内只有一个线程来执行队列中的任务, 所以task2必须等待task1执行完成才能执行
timer.schedule(task1, 1000);
timer.schedule(task2, 1000);
}
}
任务1执行时间22:21:15.248 [Timer-0]
任务2执行时间22:21:17.253 [Timer-0]
2.ScheduledExecutorService
使用ScheduledExecutorService 中schedule方法的使用
public class TestTimer {
public static void main(String[] args) {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
executor.schedule(() -> System.out.println("任务1, 执行时间:" + new Date()), 1000, TimeUnit.MILLISECONDS);
executor.schedule(() -> System.out.println("任务2, 执行时间:" + new Date()), 1000, TimeUnit.MILLISECONDS);
}
}
任务1执行时间:22:25:54
任务2执行时间:22:25:54
ScheduledExecutorService 中 scheduleAtFixedRate方法的使用
public class TestTimer {
public static void main(String[] args) {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
log.debug("start....");
// 延迟1s后, 按1s的速率打印running
executor.scheduleAtFixedRate(() -> log.debug("running"), 1, 1, TimeUnit.SECONDS);
}
}
22:51:59.930 x.TestTimer [main] - start....
22:52:01.050 x.TestTimer [pool-1-thread-1] - running
22:52:02.049 x.TestTimer [pool-1-thread-1] - running
22:52:03.045 x.TestTimer [pool-1-thread-1] - running
22:52:04.046 x.TestTimer [pool-1-thread-1] - running
22:52:05.045 x.TestTimer [pool-1-thread-1] - running
22:52:06.047 x.TestTimer [pool-1-thread-1] - running
public class TestTimer {
public static void main(String[] args) {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
log.debug("start....");
// 延迟1s后, 按1s的速率打印running
executor.scheduleAtFixedRate(() -> {
log.debug("running");
Sleeper.sleep(2);
}, 1, 1, TimeUnit.SECONDS);
}
}
// 睡眠时间 > 速率, 按睡眠时间打印
22:54:58.567 x.TestTimer [main] - start....
22:54:59.675 x.TestTimer [pool-1-thread-1] - running
22:55:01.684 x.TestTimer [pool-1-thread-1] - running
22:55:03.685 x.TestTimer [pool-1-thread-1] - running
22:55:05.690 x.TestTimer [pool-1-thread-1] - running
ScheduledExecutorService 中scheduleWithFixedDelay方法的使用
public class TestTimer {
public static void main(String[] args) {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
log.debug("start....");
// 延迟1s后, 按1s的速率打印running
// 睡眠时间 + 速率时间, 为打印的间隔时间
executor.scheduleWithFixedDelay(() -> {
log.debug("running");
Sleeper.sleep(2);
}, 1, 1, TimeUnit.SECONDS);
}
}
22:56:22.581 x.TestTimer [main] - start....
22:56:23.674 x.TestTimer [pool-1-thread-1] - running
22:56:26.679 x.TestTimer [pool-1-thread-1] - running
22:56:29.680 x.TestTimer [pool-1-thread-1] - running
22:56:32.689 x.TestTimer [pool-1-thread-1] - running
整个线程池表现为:线程数固定,任务数多于线程数时,会放入无界队列排队。任务执行完毕,这些线程也不会被释放。用来执行延迟或反复执行的任务。
3.异常处理
如果线程池中的线程执行任务时,如果任务抛出了异常,默认是中断执行该任务而不是抛出异常或者打印异常信息。
方法1:主动捕获异常
ExecutorService pool = Executors.newFixedThreadPool(1);
pool.submit(() -> {
try {
log.debug("task1");
int i = 1 / 0;
} catch (Exception e) {
log.error("error:", e);
}
});
方法2:使用 Future,错误信息都被封装进submit方法的返回方法中!
ExecutorService pool = Executors.newFixedThreadPool(1);
Future<Boolean> f = pool.submit(() -> {
log.debug("task1");
int i = 1 / 0;
return true;
});
log.debug("result:{}", f.get());
五、总结
暂无