Home »
Scala
Multithreading in Scala
By IncludeHelp Last updated : November 16, 2024
Scala Multithreading
Multithreading is the concept of using multiple threads simultaneously that allows the program to perform multiple operations simultaneously.
A thread is a lightweight sub-processes that require a very lesser amount of memory to get executed. The general multithreaded program consists of two or more thread that runs concurrently to optimize the use of resources ( multiple CPUs) and increase the performance of the program.
How Thread Works?
A thread is a lightweight process and its lifespan is defined as the time From which it starts to the point where it's terminated. In its lifespan, the thread goes from various phases. They are,
new → runnable → running → terminated
Sometimes the thread goes into the block state also.
Threads in Scala
To create a thread in Scala there are classes and methods defined. Threads in scala are created using two mechanisms,
- Extending the Thread class
- Extending the Runnable Interface
1. Creating a thread extending the Thread class
The thread class is an inbuilt Scala class that is extended to create threads. It has run() method, which is overrated to run the side object.
To create a thread we make an object of this class and then invoke the start() method which itself invokes the run() method.
Example
class MyThread extends Thread {
override def run(): Unit = {
println("Hello, This is Thread " + Thread.currentThread().getName())
}
}
object MyObject {
def main(args: Array[String]): Unit = {
for (x <- 1 to 3) {
val th = new MyThread()
th.setName(s"Thread-$x")
th.start()
}
}
}
Output
Hello, This is Thread 1
Hello, This is Thread 2
Hello, This is Thread 3
2. Creating a thread using runnable interface
Create thread using runnable interface to create a class that will implement the runnable interface and overwrites it's run() method to run a thread. Create a red Devil make an object of a class and then using this object we will call the start method that will initiate the thread and then automatically call the run() method that runs thread.
The below sample code shows how we create a thread using runnable interface:
Example
class MyThread extends Runnable {
override def run(): Unit = {
println("Hello, This is Thread " + Thread.currentThread().getName())
}
}
object myClass {
def main(args: Array[String]): Unit = {
for (x <- 1 to 3) {
val newThread = new Thread(new MyThread())
newThread.setName(x.toString())
newThread.start()
}
}
}
Output
Hello, This is Thread 1
Hello, This is Thread 2
Hello, This is Thread 3