Callable 和 Runable都是启动一个线程, 不过Callable可以有返回值
import java.util.concurrent.{Callable, Executor, Executors, Future}
object ThreadDemo {
def main(args: Array[String]): Unit = {
val pool = Executors.newFixedThreadPool(5)
// for(i <- 1 to 10) {
// pool.execute(new Runnable {
// override def run(): Unit = {
// println(Thread.currentThread().getName)
// Thread.sleep(1000)
// }
// })
// }
//开启子线程
val f :Future[Int] = pool.submit(new Callable[Int] {
override def call(): Int = {
Thread.currentThread().getName
//返回100
100
}
})
var status = f.isDone
println(s"task status : $status")
Thread.sleep(5000)
status = f.isDone
println(s"task status : $status")
//status == true的时候,取出子线程返回值:100
if(status){
println(f.get())
}
}
}
结果:
task status : false
task status : true
100
网友评论