future可以实现多线程并发,使用起来简单,但是效果很好,直接看代码吧
import java.text.SimpleDateFormat import java.util.Date import java.util.concurrent.TimeUnit import scala.concurrent.{Await, Future} import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.duration._ object FutureTest { def main(args: Array[String]): Unit = { val results = Await.result(f4, 5 seconds) println("end: " + new SimpleDateFormat("hh:mm:ss:SSS").format(new Date())) println(results) } val f1 = Future { println("f1 executing " + new SimpleDateFormat("hh:mm:ss:SSS").format(new Date())) TimeUnit.SECONDS.sleep(1) "f1" } val f2 = Future { println("f2 executing " + new SimpleDateFormat("hh:mm:ss:SSS").format(new Date())) TimeUnit.SECONDS.sleep(2) "f2" } val f3 = Future { println("f3 executing " + new SimpleDateFormat("hh:mm:ss:SSS").format(new Date())) TimeUnit.SECONDS.sleep(3) "f3" } val f4: Future[Seq[String]] = Future.sequence(Seq(f1, f2, f3)) }
结果如下:
f1 executing 10:57:10:741 f3 executing 10:57:10:741 f2 executing 10:57:10:788 end: 10:57:13:760 List(f1, f2, f3)
f1、f2、f3同时启动,说明实现了多线程并发
时间: 2024-12-29 06:55:25