Java 理解线程池
我是Java 理解线程池,java,multithreading,java.util.concurrent,Java,Multithreading,Java.util.concurrent,我是java.util.concurrent软件包的新手,因此我想征求一下建议。我需要评估线程池中的某些操作,但我还需要取消并行评估。因此,我倾向于将ThreadPoolExecutor包装到Future接口中。以下是我试图做的: public class PooledFutureTask implements Future<List<Integer>> { ExecutorService executor = Executors.newFixedThreadP
java.util.concurrent
软件包的新手,因此我想征求一下建议。我需要评估线程池中的某些操作,但我还需要取消并行评估。因此,我倾向于将ThreadPoolExecutor
包装到Future
接口中。以下是我试图做的:
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;
}
}
公共类PooledFutureTask实现未来{
ExecutorService executor=Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
取消私有布尔值;
列出结果;
公共PooledFutureTask(列出可运行项){
for(Runnable r:runnables)
执行人。执行人(r);
}
@凌驾
公共布尔值取消(布尔值可能中断刷新){
if(executor.shutdownow().size()>0)
返回取消=真;
返回executor.isTerminated()| | executor.isShutdown();
}
@凌驾
公共布尔值已取消(){
退货取消;
}
@凌驾
公共布尔isDone(){
返回executor.isTerminated();
}
@凌驾
public List get()引发InterruptedException,ExecutionException{
while(true){
if(executor.isShutdown())
返回结果;
}
}
@凌驾
公共列表获取(长超时,时间单位)
抛出InterruptedException、ExecutionException、TimeoutException{
if(执行器等待终止(超时,时间单位毫秒))
抛出新的TimeoutException();
返回结果;
}
}
但我不确定。你不能指出我错在哪里吗
我使用的是Java7。您使用的是哪个版本的Java?
虽然(true)
是可以想象的最糟糕的代码,但千万不要在任何地方使用它,它会产生意外的死锁。此语句长期以来一直是坏的/不稳定的/错误的/应用程序的根本原因。即使你设法为几乎所有可以想象到的情况(这是不可能的)创建退出路径,你仍然会编写一些实际开发人员几乎无法阅读的代码。@Specializet我知道,这就是我问这个问题的原因。但我找不到更好的解决方案。千万不要将执行者
放入任务本身,因为执行者
就像作业队列一样,无论任务或结果如何(未来
s),实例都必须存在。我认为您需要做的是扩展ExecutorService
。你真正想做什么?具体地说,应该明确显示取消策略和执行策略。@specialitThread.current().isInterrupted()
是针对while(true)
使用哪种版本的Java的最佳且唯一的解决方案?while(true)
是可以想象的最糟糕的代码段-不要在任何地方使用它,它将产生意外的死锁。此语句长期以来一直是坏的/不稳定的/错误的/应用程序的根本原因。即使你设法为几乎所有可以想象到的情况(这是不可能的)创建退出路径,你仍然会编写一些实际开发人员几乎无法阅读的代码。@Specializet我知道,这就是我问这个问题的原因。但我找不到更好的解决方案。千万不要将执行者
放入任务本身,因为执行者
就像作业队列一样,无论任务或结果如何(未来
s),实例都必须存在。我认为您需要做的是扩展ExecutorService
。你真正想做什么?具体地说,应该显式显示取消策略和执行策略。@specializetThread.current().isInterrupted()
是针对while(true)