在Java中执行简单异步任务的最佳方法? [英] Best way to execute simple async task in Java?

查看:1896
本文介绍了在Java中执行简单异步任务的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to asynchronously invoke a function which does something separately from main thread. I'm new in Java concurrency, so i ask what is the best way to perform action like this:

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

while循环继续进行,而功能 MyFileService.resize 在后台处理集合中的每个文件。

The while loop goes on while function MyFileService.resize works in background with each of my files in collection.

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

I heard that CompletionStage from Java8 could be good way to do it. What is the best way?

推荐答案

未来 Java8 中,例如:

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

对于 CompletableFuture.supplyAsync 默认将使用< a href = https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ForkJoinPool.html rel = noreferrer> ForkJoinPool公共池,默认线程大小是: Runtime.getRuntime()。availableProcessors()-1 ,也可以通过以下方式对此进行修改:

For CompletableFuture.supplyAsync default will use ForkJoinPool common pool, the default thread size is: Runtime.getRuntime().availableProcessors() - 1, also you can modify this by:


  1. System.setProperty( java.util.concurrent.ForkJoinPool.common.parallelism,size)

  2. Djava.util.concurrent.ForkJoinPool.common.parallelism = size

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

也您可以使用 supplyAsync 方法d与您自己的执行器,例如:

also you can use supplyAsync method with your own Executor, like:

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

这篇关于在Java中执行简单异步任务的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆