我第一次尝试使用期货。您可以取消工作似乎很聪明,但它没有按预期工作。在下面的示例中,只有第一个作业被取消。其余的都完成了。我误解了期货的使用吗?
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