为什么Scala Futures一次只运行2个?

时间:2015-10-22 21:27:43

标签: scala concurrency parallel-processing concurrent.futures

我正在尝试使用Scala Futures同时运行50多个任务。不幸的是,虽然我只让他们一次运行2。有人能告诉我我做错了什么或如何提高并行度?

import ExecutionContext.Implicits.global
import scala.concurrent._
import scala.concurrent.duration._

object Test {
  def main(args: Array[String]) {
    def go() = {
      val list = Seq(
          Future { println("start 1"); Thread.sleep(1000); println("stop 1")}, 
          Future { println("start 2"); Thread.sleep(2000); println("stop 2")},
          Future { println("start 3"); Thread.sleep(3000); println("stop 3")},
          Future { println("start 4"); Thread.sleep(4000); println("stop 4")},
          Future { println("start 5"); Thread.sleep(5000); println("stop 5")}
      )
      Future.sequence(list)
    }
    Await.result(go, Duration.Inf)
  }
}

我得到的结果是

start 1
start 2  
stop 1  
start 3  
stop 2  
start 4  
stop 3  
start 5  
stop 4  
stop 5

为什么我没有得到以下内容?

start 1
start 2
start 3
start 4
start 5
stop 1
stop 2
stop 3
stop 4
stop 5

2 个答案:

答案 0 :(得分:9)

与并行执行构造一样,Scala Future需要某种ExecutionContext支持它;通常,这个ExecutionContext有一个线程池,可以从中绘制以执行未来的逻辑。

使ExecutionEnvironment可用的最常见方法是将隐式定义的线程池引入范围,因此它将传递给Future构造逻辑。这是通过导入default defintion完成的,如下所示:

import scala.concurrent.ExecutionContext.implicits.global

正如您将在上面链接的api文档中看到的,此默认线程池将可用线程数设置为处理器核心数,a.k.a。

parallelism level == Runtime.availableProcessors

答案 1 :(得分:1)

得到了它!谢谢你们两个

import java.util.concurrent.Executors
import scala.concurrent._
import scala.concurrent.duration._

object Test {
  def main(args: Array[String]) {
    val executorService  = Executors.newFixedThreadPool(1000)
    val executionContext = ExecutionContext.fromExecutorService(executorService)

    def go(implicit ec: ExecutionContext) = {
      val list = Seq(
          Future { println("start 1"); Thread.sleep(1000); println("stop 1")}, 
          Future { println("start 2"); Thread.sleep(2000); println("stop 2")},
          Future { println("start 3"); Thread.sleep(3000); println("stop 3")},
          Future { println("start 4"); Thread.sleep(4000); println("stop 4")},
          Future { println("start 5"); Thread.sleep(5000); println("stop 5")}
      )
      Future.sequence(list)
    }
    Await.result(go(executionContext), Duration.Inf)
  }
}