Skip to content

Instantly share code, notes, and snippets.

@taveek
Created September 12, 2019 04:19
Show Gist options
  • Save taveek/a9c7472a7d0e8b1679bcf827363845fa to your computer and use it in GitHub Desktop.
Save taveek/a9c7472a7d0e8b1679bcf827363845fa to your computer and use it in GitHub Desktop.
ตัวอย่างการใช้งาน Future ใน Scala อย่างง่าย และการสร้าง ExecutionContext
package example
import scala.concurrent.duration.Duration
import scala.concurrent.{ Future, Await }
//import scala.concurrent.ExecutionContext.Implicits.global
object Hello extends Greeting with App {
Prog.debug("Starting Main")
val futureA = Prog.taskA()
val futureB = Prog.taskB()
Prog.debug("Finished Main")
Await.result(futureA zip futureB, Duration.Inf)
}
object Prog {
/*implicit*/ val executor = scala.concurrent.ExecutionContext.global
def taskA(): Future[Unit] = Future {
debug("Starting taskA")
Thread.sleep(1000) // wait 1secs
debug("Finished taskA")
} (executor)
def taskB(): Future[Unit] = Future {
debug("Starting taskB")
Thread.sleep(2000) // wait 2secs
debug("Finished taskB")
} (executor)
def debug(message: String): Unit = {
val now = java.time.format.DateTimeFormatter.ISO_INSTANT
.format(java.time.Instant.now)
.substring(11, 23) // keep only time component
val thread = Thread.currentThread.getName()
println(s"$now [$thread] $message")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment