Java ScheduledThreadPoolExecutor:可以在shutdownNow()之后执行List中的Runnables吗?

时间:2018-05-30 10:47:11

标签: java threadpoolexecutor

我无法在ScheduledThreadPoolExecutor对象上调用shutdownNow()后,在Runnables列表中返回Runnables(队列中的延迟任务)。

我已经尝试过一些方法:你可以获取列表大小,其中一个Runnable对象本身,调用isDone()查询,但我还没有办法运行它们。

如果可能,他们会被执行吗?

请参阅下面的代码。谢谢。

import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;

public class ExecuteExisitingDelayedTasksAfterShutdownPolicy1 {
private static int count = 0;

private static class Task implements Runnable {
    private String name;

    public Task(String name) {
        this.name = name;
        count++;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            return;
        }
        System.out.printf("\n%s: " + getName(), Thread.currentThread().getName());
    }

    public String getName() {
        return name;
    }
}

public static void main(String[] args) throws InterruptedException, ExecutionException {
    ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(10, new ThreadPoolExecutor.DiscardPolicy());
    stpe.setExecuteExistingDelayedTasksAfterShutdownPolicy(true);
    List<Runnable> queue = null;
    for (int i = 0; i < 100; i++) {
        stpe.execute(new Task("Task " + count));
        if (i == 50) {
            Thread.sleep(1000);
            queue = stpe.shutdownNow();
            System.out.print("\nQueue SIZE: " + queue.size());
        }
    }
    Thread.sleep(3000);
    System.out.print("\n" + queue.get(0));
    @SuppressWarnings("unchecked")
    FutureTask<Task> ftask = (FutureTask<Task>) queue.get(0);
    ExecutorService ses = Executors.newSingleThreadExecutor();
    /**
     * all of the next.. doesn't work: tasks returned in a queue are likely 
    to be
     * unrunnable
     */
    ftask.get().run();
    System.out.println(ftask.get().name);
    ses.execute(ftask);
    queue.get(0).run();

   }
}

0 个答案:

没有答案