相关疑难解决方法(0)

如何为Executors.newScheduledThreadPool(5)设置RemoveOnCancelPolicy

我有这个:

ScheduledExecutorService scheduledThreadPool = Executors
        .newScheduledThreadPool(5);
Run Code Online (Sandbox Code Playgroud)

然后我开始这样的任务:

scheduledThreadPool.scheduleAtFixedRate(runnable, 0, seconds, TimeUnit.SECONDS);
Run Code Online (Sandbox Code Playgroud)

我以这种方式保留对Future的引用:

ScheduledFuture<?> scheduledFuture = scheduledThreadPool.scheduleAtFixedRate(runnable, 0, seconds, TimeUnit.SECONDS);
Run Code Online (Sandbox Code Playgroud)

我希望能够取消并删除未来

scheduledFuture.cancel(true);
Run Code Online (Sandbox Code Playgroud)

然而,这个SO答案指出,取消不会删除它,并且添加新任务将在许多无法进行GC的任务中结束.

/sf/answers/1009650491/

他们提到了一些事情setRemoveOnCancelPolicy,但是这scheduledThreadPool没有这种方法.我该怎么办?

java concurrency multithreading

11
推荐指数
1
解决办法
3326
查看次数

如何等待(固定利率)ScheduledFuture 在取消时完成

是否有一种内置方法可以取消Runnable已通过固定速率安排的任务ScheduledExecutorService.scheduleAtFixedRate并等待它完成(如果它在调用取消时碰巧正在运行)?

考虑以下示例:

public static void main(String[] args) throws InterruptedException, ExecutionException  {

    Runnable fiveSecondTask = new Runnable() {
        @Override
        public void run() {
            System.out.println("5 second task started");
            long finishTime = System.currentTimeMillis() + 5_000;
            while (System.currentTimeMillis() < finishTime);
            System.out.println("5 second task finished");
        }
    };

    ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
    ScheduledFuture<?> fut = exec.scheduleAtFixedRate(fiveSecondTask, 0, 1, TimeUnit.SECONDS);

    Thread.sleep(1_000);
    System.out.print("Cancelling task..");
    fut.cancel(true);

    System.out.println("done");
    System.out.println("isCancelled : " + fut.isCancelled());
    System.out.println("isDone      : " + fut.isDone());
    try {
        fut.get();
        System.out.println("get         : didn't throw exception"); …
Run Code Online (Sandbox Code Playgroud)

java scheduledexecutorservice

6
推荐指数
1
解决办法
3040
查看次数