11

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

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
4

2 回答 2

8

Future#cancel()不会终止/中断已经运行的作业。它只会取消尚未运行的作业。

更新:polygenelubricants 确定了根本原因(+1):这是改进的代码:

int processors = Runtime.getRuntime().availableProcessors();
System.out.println("Processors: " + processors);
ExecutorService es = Executors.newFixedThreadPool(processors);
int nowork = 10;
Future<Integer>[] workers = new Future[nowork];

for (int i = 0; i < nowork; i++) {
    final int ii = i;
    workers[i] = es.submit(new Callable<Integer>() {
        public Integer call() throws Exception {
            return ii;
        }
    });
}

for (int i = 0; i < nowork; i++) {
    if (i % 2 == 0) {
        System.out.println("Cancel worker " + i);
        workers[i].cancel(true);
    }
}

for (int i = 0; i < nowork; i++) {
    if (workers[i].isCancelled()) {
        System.out.println("Worker " + i + " is cancelled");
    } else {
        System.out.println("Worker " + i + " returned: " + workers[i].get());
    }
}

es.shutdown();

结果:

处理器:2
取消工人 0
取消工人 2
取消工人 4
取消工人 6
取消工人 8
工人 0 被取消
工人 1 返回:1
工人 2 被取消
工人 3 返回: 3
工人 4 被取消
工人 5 返回:5
工人 6 被取消
工人 7 返回:7
工人 8 被取消
工人 9 返回:9

(注意它是workers,不是workres)。

于 2010-05-12T16:11:54.213 回答
8

问题是您的取消循环与您的get()循环重叠,从而阻塞。我想你想要有 2 个循环,不是吗?一个循环取消偶数作业,然后第二个循环检查哪些被取消,哪些没有,然后get()相应地检查。

它现在的编写方式,在循环甚至有机会取消之前workres[2],它检查并要求get()from workres[1]

所以我认为你需要3个阶段:

1. The `submit()` loop
2. The selective `cancel()` loop
3. The selective `get()` loop (which blocks)
于 2010-05-12T16:13:47.903 回答