在 Java 中执行简单异步任务的最佳方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41057655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way to execute simple async task in Java?
提问by Konrad Dziurd?
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:
我想异步调用一个与主线程分开执行某些操作的函数。我是 Java 并发方面的新手,所以我问执行这样的操作的最佳方法是什么:
for(File myFile : files){
MyFileService.resize(myfile) <--- this should be async
}
The while loop goes on while function MyFileService.resize
works in background with each of my files in collection.
while 循环继续 while 函数MyFileService.resize
在后台与我收集的每个文件一起工作。
I heard that CompletionStage from Java8 could be good way to do it. What is the best way?
我听说 Java8 的 CompletionStage 可能是一个很好的方法。什么是最好的方法?
回答by chengpohi
How about Futurein Java8, example:
怎么样的未来在Java8,例如:
for(File myFile : files){
CompletableFuture.supplyAsync(() -> MyFileService.resize(myfile))
}
For CompletableFuture.supplyAsync
default will use ForkJoinPool common pool, the default thread size is: Runtime.getRuntime().availableProcessors() - 1
, also you can modify this by:
对于CompletableFuture.supplyAsync
默认将使用ForkJoinPool公共池,默认的线程大小:Runtime.getRuntime().availableProcessors() - 1
,你也可以通过修改此:
System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", size)
Djava.util.concurrent.ForkJoinPool.common.parallelism=size
System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", size)
Djava.util.concurrent.ForkJoinPool.common.parallelism=size
also you can use supplyAsync
method with your own Executor, like:
您也可以将supplyAsync
方法与您自己的Executor 一起使用,例如:
ExecutorService executorService = Executors.newFixedThreadPool(20);
CompletableFuture.supplyAsync(() -> MyFileService.resize(myfile), executorService)
回答by GhostCat
The "most simple" straight forward solution is to create a "bare metal" Thread on the fly and have it call that method. See herefor details.
“最简单”的直接解决方案是动态创建一个“裸机”线程并让它调用该方法。有关详细信息,请参见此处。
Of course, programming is always about adding levels of abstractions; and in that sense, you can look into using an ExecutorService. And as you are mentioning java8, this herewould be a good starting point (that also shows how to use ordinary Threads in a more java8 style).
当然,编程总是要增加抽象层次;从这个意义上说,您可以考虑使用 ExecutorService。而当你被提java8,这这里将是一个很好的起点(也展示了如何在一个更加java8风格使用普通线程)。
回答by Thomas Philipp
Most simple would be (with Java 8):
最简单的是(使用 Java 8):
for(File myFile : files){
new Thread( () -> MyFileService.resize(myfile)).start();
}