码迷,mamicode.com
首页 > 编程语言 > 详细

scala多线程

时间:2017-03-27 17:04:57      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:res   end   return   new t   imp   import   extend   new   .exe   

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执行完有返回值Runnable执行完无返回值

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()
    }
  }
}

  

scala多线程

标签:res   end   return   new t   imp   import   extend   new   .exe   

原文地址:http://www.cnblogs.com/nicebaby/p/6627598.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!