gpt4 book ai didi

java - 关闭 ScheduledExecutorService 是否安全?

转载 作者:行者123 更新时间:2023-11-30 06:52:47 25 4
gpt4 key购买 nike

我正在实现一项服务,该服务执行一些运行时间较长的任务,由此处的 Thread.sleep(10000) 模拟。当我按 ctrl+c 执行时,我从未得到我期望的 InterruptedException。我想知道为什么。

package simple;

import my.util.Now;
import io.dropwizard.lifecycle.Managed;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class EmailSender implements Managed {

private static final Logger LOGGER = LoggerFactory.getLogger(EmailSender.class);
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(3);

// Constructor
public EmailSender() {}

@Override
public void start() {
LOGGER.info("Starting email sender thread: {}", Thread.currentThread().getName());
Runnable task = () -> {
LOGGER.info("Running: {} in thread: {}", Now.now(), Thread.currentThread().getName());
try {
Thread.sleep(10000);
} catch (InterruptedException ie) {
LOGGER.error("Task is being interrupted: {}", ie.getMessage());
}
};
executorService.scheduleAtFixedRate(task, 0, 5, TimeUnit.SECONDS);
}

@Override
public void stop() {
LOGGER.info("Stopping email sender thread: {}", Thread.currentThread().getName());
executorService.shutdown();

}
}

假设 executorService.shutdown(); 以这种方式等待任务执行结束是否安全?

最佳答案

shutdown 不会终止当前正在运行的任务,它甚至会执行队列中等待的任务。

使用shutdownNow如果你想立即终止。

关于java - 关闭 ScheduledExecutorService 是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38409697/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com