将executor.submit的结果存储到Stringbuffer.append

时间:2017-08-04 04:37:48

标签: java multithreading executorservice

我有Executors.newfixedThreadPool()调用提交,显然提交返回将来包装的StringBuffer对象。我需要在响应StringBuffer中附加结果。我可以在List<Future<StringBuffer>>中获得结果,然后再次迭代以追加StringBuffer。但我想在单次迭代中执行此操作,如下所示但是它附加的未来对象。有什么方法可以达到这个目的吗?

    ExecutorService es = Executors.newFixedThreadPool(count);
    for (int i = 0; i < count; i++) {
        response.append(es.submit(new Callable<StringBuffer>() {
            @Override
            public StringBuffer call() {
                StringBuffer res = new StringBuffer();
                res = processAddresses(addresses, addressLatch);
                return res;
            }
        }));
    }
    try {
        addressLatch.await();       
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    es.shutdownNow();

1 个答案:

答案 0 :(得分:0)

你可以这样做:

    final StringBuffer response = new StringBuffer();
    ExecutorService es = Executors.newFixedThreadPool(count);
    for (int i = 0; i < count; i++) {
        es.submit(new Runnable() {
            @Override
            public void run() {
                StringBuffer res = processAddresses(addresses, addressLatch);
                response.append(res);
            }
        });
    }
    es.shutdownNow();
    try {
        es.awaitTermination(1, TimeUnit.HOURS);
    } catch (InterruptedException ex) {
        LOG.log(Level.SEVERE, null, ex);
    }
    System.out.println(response);

但订单没有被保留