public ScheduledFuture<?> executeTaskWithDelay(String name,
final Runnable runnable, Period delay, boolean isDaemon) {
ScheduledExecutorService executorService =
Executors.newSingleThreadScheduledExecutor(new DefaultThreadFactory(
name, isDaemon));
ScheduledFuture<?> future = executorService.schedule(runnable,
delay.toStandardDuration().getMillis(), TimeUnit.MILLISECONDS);
executorService.shutdown();
return future;
}
当我分析应用程序时,我注意到此方法创建的计划线程在执行之前始终处于“正在运行”而不是“等待”状态。如果我删除 executorService.shutdown() 它会做我想要的(即线程保持等待状态,直到它们运行的时间)。但是,如果没有 executorService.shutdown(),非守护线程在执行后永远不会被垃圾回收。有没有办法可以确保线程在执行前始终处于等待状态?或者我可以为这种方法使用什么其他替代品来确保:
- 我可以将前缀附加到在执行程序服务中运行的线程的名称(这实际上是 DefaultThreadFactory 实现所做的)
- 非守护线程在执行后获得 GC。
- 创建的线程保持等待状态,直到它们运行的时间。