I share example how to execute Multi-Threading in parallel on Kotlin, is very useful if you want send a lot process simultaneously, In java you can use parallel stream and exist a lot examples, but it's almost the same.
I use an ExecutorService to manage pools of threads.
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
fun main(args: Array<String>) {
println("Started.....!")
var listStr = arrayOf("test1", "test2", "test3",
"test4", "test5", "test6", "test7", "test8", "test9", "test10")
var es = Executors.newCachedThreadPool()
for (item in listStr) {
es.execute {
println("item -> $item")
}
}
es.shutdown()
var finished = es.awaitTermination(1, TimeUnit.MINUTES)
println("\\nFinished all threads $finished")
}
Run test: check test 3 execute after test 4 and test 2 execute after test 3.
References:
https://winterbe.com/posts/2015/04/07/java8-concurrency-tutorial-thread-executor-examples/
https://howtodoinjava.com/java/multi-threading/executorservice-invokeall/
https://crunchify.com/how-to-run-multiple-threads-concurrently-in-java-executorservice-approach/
https://stackoverflow.com/questions/7939257/wait-until-all-threads-finish-their-work-in-java
No comments:
Post a Comment