Things to know about Multithreading in Scala

Reading Time: 5 minutes

What is Scala 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.

What is Scala Threads?

In Scala, a thread is a lightweight sub-process that occupies less memory. To create a Thread, we can either extend the Thread class or the Runnable interface. We can use the run() method to run the thread.
Threads hold less memory than a full-blown process.
Let’s take a look at its life cycle.

Scala Threads Life cycle

A thread’s life cycle is an account of when it begins and ends. It has five states:

  1. New – This is effectively the first state for 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 the 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 in dead.

How to Create Thread in Scala?

In Scala, Thread is created by two steps:

1. By Extending the Thread class

class Method1 extends Thread {
  override def run(): Unit ={
    println("Hello, This is Thread by extending Thread class " + Thread.currentThread().getName )
  }
}
object main extends App {
    for (x <- 1 to 3){
      val th1 = new Method1()
      th1.setName(x.toString)
      th1.start()
    }
}

2. By Extending the Runnable Interface

class Method2 extends Runnable{
  override def run(): Unit ={
    println("Hello, This is Thread by using the runnable  " + Thread.currentThread().getName )
  }
}
object main extends App {
  for (x <- 1 to 3){
    val th2 = new Thread(new Method2())
    th2.setName(x.toString)
    th2.start()
  }
}

Scala Thread Methods

Here, we discussed the states in a Scala thread life-cycle.
We can also control thread flow to deal with these states by using these methods.


Let’s take a few examples.

1. sleep()

We can use this method to put a thread to sleep for a number of milliseconds.
Let’s take an example.

class SleepMethods extends Thread {

  // sleep methods
  override def run(): Unit = {
    for (i <- 1 to 5) {
      println(i)
      Thread.sleep(300)
    }
  }
}
object main extends App {
  var d1= new Thread(new SleepMethods())
   d1.start()
}

Output:
1
2
3
4
5

2. join()

In Scala, the Join method is used to hold the execution of the Scala thread currently running until it finishes the execution.
It also waits for a thread to die before it can start more.

class JoinMethod extends Thread{
// join() method
  override def run(): Unit = {
    for (i <- 1 to 4) {
      println(i)
      Thread.sleep(400)
    }
  }
}
object main extends App {
  var thread1= new Thread(new JoinMethod())
  var thread2= new Thread(new JoinMethod())
  var thread3= new Thread(new JoinMethod())
  thread1.start()
  thread1.join()
  thread2.start()
  thread3.start()
}



Output:
1
2
3
4
1
1
2
2
3
3
4
4

In the above code, we call start() on thread1, then join() on the same object. Then, we call start() on objects thread2 and thread3.This calls start() on thread1 , then join() executes it until it dies. And then, it calls start() on thread2 and thread3, and they run.

3. setName() and getName()

These methods setName() and getName() are used to set and get names of threads. Let’s see how.

class SetNameGetName extends Thread{

  override def run(): Unit ={
    for (i <- 1 to 3) {
      println("Hello, " +this.getName+i )
      Thread.sleep(400)
    }
  }
}
object main extends App {
  var thread1= new Thread(new SetNameGetName())
  thread1.setName("0")
  thread1.start()
}

Output:
Hello, Thread-01
Hello, Thread-02
Hello, Thread-03

4.setName() and getName()

By using these methods, we can get and set the priority for a thread in Scala. Let’s take an example

class SetPriorityGetPriority extends Thread {

  override def run(): Unit = {
    for (i <- 1 to 3) {
      println(this.getName)
      println(this.getPriority)
      Thread.sleep(400)
    }
  }
}
object main extends App {
  var thread1= new Thread(new SetPriorityGetPriority())
  var thread2= new Thread(new SetPriorityGetPriority())
  thread1.setName("One")
  thread2.setName("Two")
  thread1.setPriority(Thread.MIN_PRIORITY)
  thread2.setPriority(Thread.MAX_PRIORITY)
  thread1.start()
  thread2.start()
}

Output:
Thread-2
Thread-0
5
5
Thread-0
Thread-2
5
5
Thread-2
5
Thread-0
5

5.task()

In this, we create multiple threads in Scala and use them to run multiple tasks. This lets an example-

class TaskDemo extends Thread{
  override def run(): Unit = {
    for(i<-1 to 3){
      println(i)
      Thread.sleep(400)
    }
  }
  def task(): Unit = {
    for(i<-4 to 6){
      println(i)
      Thread.sleep(200)
    }
  }
}
object main extends App {
  var d1= new Thread(new TaskDemo())
  d1.start()
  d1.task()
}


Output:
1
4
2
5
6
3

6. More methods :

1.Public static void sleep(long millis) throws InterruptedException-

In this, we used to puts the thread to sleep for a certain number of milliseconds.

 2.Public final String getName()

In this, we used to get the name of the thread.

3.Public final void setName(String name)

In this method, it is used to set the name of the thread.

4.Public final int getPriority()

This method provides us with the priority of the thread.

5.Public final void setPriority(int newPriority)

In this method, it is used to set priority for a thread.

6. Public final boolean isAlive()

This method is used to find if a thread is alive (somewhere between states New and Terminated).

7.Public final void join() throws InterruptedException

In this method, it is used to wait for the thread to die before starting another.

8.Public static void yield()

In this method, it is used to compel the currently running thread to give up control to other threads. This method also pauses the current thread.

9.Public Thread.State getState()

This method returns the state of the thread. It is used for the monitor system state.

Conclusion

In the above tutorial, we have learned about multithreading in Scala is an essential part that every Scala developer should be aware of. Multithreading is very helpful in making the program efficient and it also reduces the usage of storage resources. Multithreading actually makes the CPUs be utilized optimally to perform well regardless of their complexity. In this, both Scala methods of implementation of Multithreading offer the way and make it popular among developers.

Knoldus

Written by 

Pappu Bhardwaj is a Software Intern at Knoldus Inc. in Noida. He has completed his B.Tech from the KIET Group of Institution, Ghaziabad. He is recognized as a good team player, a dedicated and responsible professional, and a technology enthusiast. He is a quick learner & curious to learn new technologies. He is passionate about Competetive Programming. He loves to play cricket and wildlife photography.