在Java中执行简单异步任务的最佳方法?

Kon*_*rdź 3 java concurrency asynchronous

我想异步调用一个与主线程分开的函数.我是Java并发的新手,所以我问这样做的最佳方法是什么:

for(File myFile : files){
    MyFileService.resize(myfile)  <--- this should be async
}
Run Code Online (Sandbox Code Playgroud)

while循环继续,而函数MyFileService.resize在后台运行,我的每个文件都在集合中.

我听说Java8的CompletionStage可能是很好的方法.什么是最好的方法?

che*_*ohi 10

怎么样的未来在Java8,例如:

for(File myFile : files){
    CompletableFuture.supplyAsync(() -> MyFileService.resize(myfile))
}
Run Code Online (Sandbox Code Playgroud)

对于CompletableFuture.supplyAsync默认将使用ForkJoinPool公共池,默认的线程大小:Runtime.getRuntime().availableProcessors() - 1,你也可以通过修改此:

  1. System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", size)
  2. Djava.util.concurrent.ForkJoinPool.common.parallelism=size

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

ExecutorService executorService = Executors.newFixedThreadPool(20);
CompletableFuture.supplyAsync(() -> MyFileService.resize(myfile), executorService)
Run Code Online (Sandbox Code Playgroud)