Scala program to set and get the name of the thread

Here, we are going to learn how to set and get the name of the thread in Scala programming language?
Submitted by Nidhi, on July 17, 2021 [Last updated : March 12, 2023]

Scala - Setting and Getting Thread's Name

Here, we will set and get the name of the thread using the setName() and getName() methods.

Scala code to set and get the name of the thread

The source code to set and get the name of the thread is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to set and get the name of thread

class MyThread extends Thread {
  override def run() {
    var cnt: Int = 0;

    while (cnt < 5) {
      printf("%s: %d\n", this.getName(), cnt);
      cnt = cnt + 1;
    }
  }
}

object Sample {
  // Main method
  def main(args: Array[String]) {
    var thrd1 = new MyThread();
    var thrd2 = new MyThread();

    thrd1.setName("Thread1")
    thrd2.setName("Thread2")

    thrd1.start();
    thrd2.start();
  }
}

Output

Thread2: 0
Thread2: 1
Thread2: 2
Thread2: 3
Thread1: 0
Thread1: 1
Thread1: 2
Thread1: 3
Thread1: 4
Thread2: 4

Explanation

Here, we created a class MyThread by implementing the Runnable interface and the implement run() method.

We created a class MyThread by extending the Thread class and implement the run() method.

In the main() function, we created two threads and set the name of the thread using the setName() method, and get the name of the thread in the run() method using the getName() method.

Scala Threading Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.