Created
February 1, 2018 03:50
-
-
Save notyy/73a7562f103a6d5a77c097c40cba7a73 to your computer and use it in GitHub Desktop.
future in different thread
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package concurrency.future | |
import com.typesafe.scalalogging.StrictLogging | |
import scala.concurrent.{Await, Future} | |
import scala.concurrent.duration._ | |
import scala.language.postfixOps | |
import scala.concurrent.ExecutionContext.Implicits.global | |
object FutureAwait extends App with StrictLogging { | |
logger.info("now") | |
def doSomethingInFuture: Future[Int] = Future { | |
logger.info("this is in future") | |
1 | |
} | |
val rs = Await.result(doSomethingInFuture, 1 second) | |
logger.info(s"rs is $rs") | |
} |
thread pool
import scala.concurrent.{Await, Future, Promise}
import scala.concurrent.duration._
import scala.language.postfixOps
import scala.concurrent.ExecutionContext
import java.util.concurrent.Executors
object FutureAwait extends App{
val threadPool = Executors.newFixedThreadPool(1);
implicit val ec = new ExecutionContext {
def execute(runnable: Runnable) {
threadPool.submit(runnable)
}
def reportFailure(t: Throwable) {}
}
println(s"${Thread.currentThread().getName}\tbefore start")
def doSomethingInFuture(i: Int): Future[Int] = Future {
Thread.sleep(100)
println(s"${Thread.currentThread().getName}\tthis is in the future($i)")
i
}
for {
i <- 1 to 10
x <- doSomethingInFuture(i)
} {
println(s"${Thread.currentThread().getName}\tthis is in futrue($i) success callback")
}
println(s"${Thread.currentThread().getName}\tbefore sleep 10s")
Thread.sleep(10000)
println(s"${Thread.currentThread().getName}\tafter sleep 10s")
println(s"${Thread.currentThread().getName}\tbefore await")
val rs = Await.result(doSomethingInFuture(100), 1 second)
println(s"result ${rs}")
println(s"${Thread.currentThread().getName}\tafter await")
threadPool.shutdown()
}
赞, 可以用 ExecutionContext.fromExecutor 简化一下:)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
single thread