scala學習筆記:理解並行集合par

白喬發表於2015-02-28
scala> (1 to 5).foreach(println(_))
1
2
3
4
5

scala> (1 to 5).par.foreach(println(_))
3
1
4
2
5

以下程式碼獲取到參與平行計算的執行緒:

scala> (0 to 10000).collect{case _ => Thread.currentThread.getName}.distinct
res53: scala.collection.immutable.IndexedSeq[java.lang.String] = Vector(Thread-57)

scala> (0 to 10000).par.collect{case _ => Thread.currentThread.getName}.distinct
res54: scala.collection.parallel.immutable.ParSeq[java.lang.String] = ParVector(ForkJoinPool-1-worker-0, ForkJoinPool-1-worker-4, ForkJoinPool-1-worker-5, ForkJoinPool-1-worker-2, ForkJoinPool-1-worker-6, ForkJoinPool-1-worker-1, ForkJoinPool-1-worker-7)

相關文章