3

下面是该类的源代码。

shutdownNow()我想验证未提交的任务是如何工作的。我在下面的代码中遇到的问题是shutdownNow()返回List<FutureTask>,而不是List<Runnable>我提交List<Runnable>的包含提交的PrimeProducer.

In Below program I wanted to get the tasks which where not executed and their state so that I can reschedule them later. name() represents just state that I want to store.

所以我无法转换为提交的任务。

class PrimeProducer implements Runnable {
private final SynchronousQueue<BigInteger> queue;

PrimeProducer(SynchronousQueue<BigInteger> queue) {
    this.queue = queue;
}

public void run() {
    try {
        BigInteger p = BigInteger.ONE;
        queue.put(p = p.nextProbablePrime());
    } catch (InterruptedException consumed) {
        System.out.println("Safe Exit");
        Thread.currentThread().interrupt();
    }

}

public String name() {
    return "PrimeProducer";
}

public static void main(String[] args) throws InterruptedException,
        ExecutionException {
    PrimeProducer primeProducer = new PrimeProducer(
            new SynchronousQueue<BigInteger>());//SynchronousQueue just to ensure it put is blocking
    ExecutorService executorService = Executors.newFixedThreadPool(1);
    executorService.submit(primeProducer);
    executorService.submit(primeProducer);
    List<Runnable> list = executorService.shutdownNow();
    //PrimeProducer producer = (PrimeProducer) list.get(0);// Class Cast
                                                            // Exception
    FutureTask<PrimeProducer> futureTask = (FutureTask<PrimeProducer>) list
            .get(0);
            System.out.println(futureTask.isDone());//Prints false
    futureTask.get().name();//futureTask-->PrimeProducer get() hangs.


}
}

有问题的线路

//PrimeProducer producer = (PrimeProducer) list.get(0);// Class Cast
                                                            // Exception
 FutureTask<PrimeProducer> futureTask = (FutureTask<PrimeProducer>) list
            .get(0);
 futureTask.get().name();//futureTask-->PrimeProducer get() hangs.
4

2 回答 2

2

尝试“执行”而不是“提交”。

于 2012-09-19T11:43:27.897 回答
0

发生此行为是因为提交的任务的方式execute和处理方式之间存在差异。submit

execute方法直接使用Runnable commandwhich 传递给它 where as submitcreateRunnableFuture和 callexecute

 RunnableFuture<Object> ftask = newTaskFor(task, null);
于 2012-09-19T11:57:12.020 回答