completableFuture任务应该使用main方法任务独立执行

时间:2018-04-18 07:45:33

标签: java io stream completable-future

如果我为每个completableFuture任务调用future.get(),那么只有我的功能可以同时编写多个文件。 但是如果我删除future.get()代码,那么编写多个文件就不行了。为此我应该添加future.get()代码。

仅供参考我从main方法调用下面的方法,但这里发生的是,在通过调用方法完成所有任务之前,我的主方法线程也等待完成并停止执行main方法的其他代码。 但我的目的是它应该调用主线程中的其他代码,并且调用方法应该异步工作。它不应该影响我的主要方法代码。 那么你可以帮我按照我的要求实施。

以下是相同的代码: -

  private static void createCompletableFuture(ByteArrayOutputStream baOS, int totalBytes, 
            List<FileUploadMultiLocator> fileUploadList) {
        ExecutorService threadPool = Executors.newFixedThreadPool(4);
        for (FileUploadMultiLocator fileUploadMultiLocator : fileUploadList) {
            CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() ->{
                System.out.println(Thread.currentThread().getName() + " secondary task is called");
                fileUploadMultiLocator.baOS.write(baOS.toByteArray(), 0, totalBytes);
                fileUploadMultiLocator.setTotalBytes(totalBytes);
                threadPool.execute(fileUploadMultiLocator);
                 return 20;
            },threadPool);
            try {
                 future.get();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ExecutionException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        threadPool.shutdown();
        try {
            threadPool.awaitTermination(1, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
         return;
    }

1 个答案:

答案 0 :(得分:0)

你在createCompletableFuture方法中进行了异步调用,但我猜你是从主线程中调用这个方法,这就是你的主线程等待createCompletableFuture返回的原因。使用另一个线程从main方法调用此方法。