Scala基础—多线程示例

来源:互联网 发布:漫画绘图软件免费下载 编辑:程序博客网 时间:2024/05/19 22:03

原文:https://my.oschina.net/u/877759/blog/501733

写的一个scala多线程的小demo,以备后用

Runnable/Callable

区别:Runnable无返回值,Callable线程执行完有返回值


Runnable示例

import java.util.concurrent.{ExecutorsExecutorService}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.{CallableFutureTaskExecutorsExecutorService}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()    }  }}

原创粉丝点击