我正在实现一项服务,该服务可以执行一些更长的运行任务,这些任务在此由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/