Java线程池

时间:2022-05-12
本文章向大家介绍Java线程池,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

CallableRunable都是启动一个线程, 不过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