2016-12-09 22 views
1

我想异步调用一个独立于主线程的函数。我在Java并发新的,所以我问什么是这样执行操作的最佳方式:在Java中执行简单的异步任务的最佳方法?

for(File myFile : files){ 
    MyFileService.resize(myfile) <--- this should be async 
} 

while循环继续,同时在后台与我的每一个在集合文件功能MyFileService.resize作品。

我听说Java8的CompletionStage可能是实现它的好方法。 什么是最好的方法?

回答

3

如何FutureJava8,例如:

for(File myFile : files){ 
    CompletableFuture.supplyAsync(() -> MyFileService.resize(myfile)) 
} 

对于CompletableFuture.supplyAsync默认将使用ForkJoinPool common pool,默认的螺纹尺寸是:

  1. System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", size)Runtime.getRuntime().availableProcessors() - 1,你也可以通过修改本
  2. Djava.util.concurrent.ForkJoinPool.common.parallelism=size

也可以使用supplyAsync方法与自己的Executor,如:

ExecutorService executorService = Executors.newFixedThreadPool(20); 
CompletableFuture.supplyAsync(() -> MyFileService.resize(myfile), executorService) 
1

“最简单”的直接解决方案是即时创建一个“裸机”线程并让它调用该方法。详情请参阅here

当然,编程总是关于增加抽象层次;从这个意义上讲,你可以看看使用ExecutorService。当你提到java8时,这个here将是一个很好的起点(它也显示了如何在更多java8风格中使用普通线程)。

0

最简单的将是(与Java 8):

for(File myFile : files){ 
    new Thread(() -> MyFileService.resize(myfile)).start(); 
} 
相关问题