Java线程池

作者: sparkle123 | 来源:发表于2018-04-24 14:47 被阅读0次

    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
    

    相关文章

      网友评论

        本文标题:Java线程池

        本文链接:https://www.haomeiwen.com/subject/chrjlftx.html