How can I execute multiple tasks in Scala?

后端 未结 4 1193
挽巷
挽巷 2021-01-30 04:33

I have 50,000 tasks and want to execute them with 10 threads. In Java I should create Executers.threadPool(10) and pass runnable to is then wait to process all. Scala as I under

4条回答
  •  甜味超标
    2021-01-30 04:39

    Here's another answer similar to mpilquist's response but without deprecated API and including the thread settings via a custom ExecutionContext:

    import java.util.concurrent.Executors
    import scala.concurrent.{ExecutionContext, Await, Future}
    import scala.concurrent.duration._
    
    val numJobs = 50000
    var numThreads = 10
    
    // customize the execution context to use the specified number of threads
    implicit val ec = ExecutionContext.fromExecutor(Executors.newFixedThreadPool(numThreads))
    
    
    // define the tasks
    val tasks = for (i <- 1 to numJobs) yield Future {
      // do something more fancy here
      i
    }
    
    // aggregate and wait for final result
    val aggregated = Future.sequence(tasks)
    val oneToNSum = Await.result(aggregated, 15.seconds).sum
    

提交回复
热议问题