Scala uses multithreaded examples

Source: Internet
Author: User
Tags thread class

Write a scala multi-threaded demo to prepare for later use

Runnable/callable

Difference:runnable no return value,callable thread executes with return value


runnable Example

Import java.util.concurrent. {Executors, executorservice}object test {  def main (args: Array[String])  {    //creating a thread pool     val threadpool:executorservice= Executors.newfixedthreadpool (5)     try {      //commit 5 threads       for (i <- 1 to 5) {         //threadpool.submit (New threaddemo ("thread" +i)          threadpool.execute (New threaddemo ("thread" +i)       }     }finally {      threadpool.shutdown ()      }  }  //define thread class, sleep 100 milliseconds per print   class threaddemo (threadname:string)   Extends runnable{    override def run () {       for (i&NBSP;&LT;-&NBSP;1&NBSP;TO&NBSP;10) {        println (threadName+ "|" +i)         thread.sleep (+)       }     }  }}


Callable Example

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 (+)           return  "im  Result "&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;}&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;})        threadpool.execute (future)       println (Future.get ())     }finally {      threadpool.shutdown ()     }  }} 


Scala uses multithreaded examples

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.