我想第一次使用期貨。看起來很聰明,你可以取消一份工作,但它沒有按預期工作。在下面的例子中,只有第一份工作被取消。其餘完成。我誤解了對期貨的使用嗎?瞭解未來/線程
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
[email protected] 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()是一種阻止問題的方法。 – 2010-05-12 16:40:50