Scala | Multithreading

Reading Time: 2 minutes

What is Multithreading

Multithreading means we can execute multiple threads at once. We can also perform multiple operations independently and achieve multitasking. This helps us to develop concurrent applications. In Scala, a thread is a lightweight sub-process that occupies less memory. Let’s see how Scala creates threads and achieves multithreading.

What Scala Thread Life Cycle Looks Like

Scala-thread-life-cycle

In between the period of creation and Termination of a Scala Thread, the thread undergoes various state changes. These constitute the Life Cycle of a Scala Thread. It has the five following states.

  1. New – This is effectively the first state for the creation of Scala Thread.
  2. Runnable– In this state, the thread has been created but the thread scheduler hasn’t selected this thread for running. It is in a runnable state.
  3. Running– When the thread scheduler has selected a thread, then it starts running.
  4. Waiting– In this state, the thread is alive, but waiting for input or resources.
  5. Terminated– When the run() method exits, then the thread wents up dead.

How to Create Thread in Scala?

Threads in Scala can be created by using two mechanisms :

  1. Extending the Thread class
  2. Extending the Runnable Interface

Thread creation by extending the Thread class

We create a class that extends the Thread class. This class overrides the run() method available in the Thread class. A thread begins its life inside the run() method. We create an object of our new class and call the start() method to start the execution of a thread. Start() invokes the run() method on the Thread object.

//Sample Code
class ThreadExample extends Thread{  
override def run(){  
println("Thread is running...");  
}  
}  
object MainObject{  
def main(args:Array[String]){  
var t = new ThreadExample()  
t.start()  
}  
}  

Thread creation by Extending Runnable Interface

We create a new class that extends the Runnable interface and override the run() method. Then we instantiate a Thread object passing the created class to the constructor. We then call the start() method on this object.

//Sample Code
class MyThread extends Runnable 
{
override def run()
{
println("Thread " + Thread.currentThread().getName() +" is running.")
}
} 
object MainObject
{
def main(args: Array[String])
{
for (x <- 1 to 5) 
{
var th = new Thread(new MyThread()
th.setName(x.toString())
th.start()
}
}
}

Conclusion

Multithreading in Scala is one of the base concepts to implement concurrency with multiple threads working on different functions or features at the same time.

knoldus

Leave a Reply