List< Runnable>从shutdownNow()返回的值不能转换为已提交的Runnable [英] List<Runnable> returned from shutdownNow() can not be converted to submitted Runnable
问题描述
下面是该类的源代码.
我想验证shutdownNow()
如何处理未提交的任务.问题我在下面的代码中得到的是shutdownNow()
返回List<FutureTask>
而不是List<Runnable>
,我提交的List<Runnable>
包含提交的PrimeProducer
实例.
I wanted to verify how does shutdownNow()
works for not submitted task. Problem I am getting in below code is shutdownNow()
return List<FutureTask>
and not List<Runnable>
which I have submitted List<Runnable>
containing submitted instance of 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.
所以我无法转换为已提交的任务.
So I am not able to convert to submitted Task.
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.
推荐答案
尝试执行"而不是提交".
Try "execute" instead of "submit".
这篇关于List< Runnable>从shutdownNow()返回的值不能转换为已提交的Runnable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!