Scala Basics-multithreaded Example

Source: Internet
Author: User
Tags sleep thread class

Original: https://my.oschina.net/u/877759/blog/501733

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 () {   &nbsP;  for (i <- 1 to 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 "        }       })   
    threadpool.execute (future)       println (Future.get ())     }finally {      threadpool.shutdown()     }   }} 

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.