首页 > 代码库 > scala多线程
scala多线程
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多线程
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。