scala多线程
Posted 且穷且独立
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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多线程的主要内容,如果未能解决你的问题,请参考以下文章