我是java.util.concurrent
套餐的新手,所以我想问一个建议。我需要在ThreadPool中评估一些操作,但我还需要取消并发评估。所以,我倾向于将ThreadPoolExecutor
包装到Future<T>
接口中。这是我试图做的:
public class PooledFutureTask implements Future<List<Integer>> {
ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
private boolean cancelled;
List<Integer> result;
public PooledFutureTask(List<Runnable> runnables) {
for (Runnable r : runnables)
executor.execute(r);
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
if (executor.shutdownNow().size() > 0)
return cancelled = true;
return executor.isTerminated() || executor.isShutdown();
}
@Override
public boolean isCancelled() {
return cancelled;
}
@Override
public boolean isDone() {
return executor.isTerminated();
}
@Override
public List<Integer> get() throws InterruptedException, ExecutionException {
while(true) {
if (executor.isShutdown())
return result;
}
}
@Override
public List<Integer> get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
if (executor.awaitTermination(timeout, TimeUnit.MILLISECONDS))
throw new TimeoutException();
return result;
}
}
但我不确定。难道你不能指出我错在哪里吗?
我正在使用Java7。