Scala高階之多線程

Runnable/Callable

入門級區別:Runnable無返回值,Callable線程執行完有返回值。

深入源碼後面會詳解。

Runnable示例

import java.util.concurrent.{Executors, ExecutorService}
 
object Test {
  def main(args: Array[String]) {
    //創建線程池
    val threadPool:ExecutorService=Executors.newFixedThreadPool(5)
    try {
      //提交5個線程
      for(i <- 1 to 5){
        //threadPool.submit(new ThreadDemo("thread"+i))
        threadPool.execute(new ThreadDemo("thread"+i))
      }
    }finally {
      threadPool.shutdown()
    }
  }
 
  //定義線程類,每打印一次睡眠100毫秒
  class ThreadDemo(threadName:String) extends Runnable{
    override def run(){
      for(i <- 1 to 10){
        println(threadName+"|"+i)
        Thread.sleep(100)
      }
    }
  }
}

Callable示例

 

import java.util.concurrent.{Callable, FutureTask, Executors, ExecutorService}
 
object Test {
  def main(args: Array[String]) {
    val threadPool:ExecutorService=Executors.newFixedThreadPool(3)
    try {
      val future=new FutureTask[String](new Callable[String] {
        override def call(): String = {
          Thread.sleep(100)
          return "im result"
        }
      })
      threadPool.execute(future)
      println(future.get())
    }finally {
      threadPool.shutdown()
    }
  }
}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章