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() } }}