我试图第一次使用期货.看起来很聪明,你可以取消一份工作,但它不能按预期工作.在下面的示例中,只有第一个作业被取消.其余的完成了.我误解了期货的使用吗?
public class ThreadExample { public static void main(String[] args) throws InterruptedException,ExecutionException { int processors = Runtime.getRuntime().availableProcessors(); System.out.println("Processors: " + processors); ExecutorService es = Executors.newFixedThreadPool(processors); int nowork = 10; Future<Integer>[] workres = new Future[nowork]; for(int i = 0; i < nowork; i++) { workres[i] = es.submit(new SomeWork(i)); } for(int i = 0; i < nowork; i++) { if(i % 2 == 0) { System.out.println("Cancel"); workres[i].cancel(true); } if(workres[i].isCancelled()) { System.out.println(workres[i] + " is cancelled"); } else { System.out.println(workres[i].get()); } } es.shutdown(); } } class SomeWork implements Callable<Integer> { private int v; public SomeWork(int v) { this.v = v; } @Override public Integer call() throws Exception { TimeUnit.SECONDS.sleep(5); System.out.println(v + " done at " + (new Date())); return v; } }
输出:
Processors: 4 Cancel java.util.concurrent.FutureTask@10d448 is cancelled 4 done at Wed May 12 17:47:05 CEST 2010 2 done at Wed May 12 17:47:05 CEST 2010 1 done at Wed May 12 17:47:05 CEST 2010 3 done at Wed May 12 17:47:05 CEST 2010 1 Cancel 2 3 Cancel 4 5 done at Wed May 12 17:47:10 CEST 2010 7 done at Wed May 12 17:47:10 CEST 2010 8 done at Wed May 12 17:47:10 CEST 2010 6 done at Wed May 12 17:47:10 CEST 2010 5 Cancel 6 7 Cancel 8 9 done at Wed May 12 17:47:15 CEST 2010 9
解决方法
问题是您的取消循环与您的get()循环重叠,阻塞.我想你想要有2个循环,不是吗?一个循环取消偶数编号的作业,然后取消第二个循环,检查哪些已被取消,哪些不被取消,然后取得相应的get().
它现在写的方式,在循环之前甚至有机会取消工作[2],它检查并请求工作的get()[1].
所以我想你需要3个阶段:
1. The `submit()` loop 2. The selective `cancel()` loop 3. The selective `get()` loop (which blocks)