Q:

Scala program to set and get the name of the thread

belongs to collection: Scala Threading Programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

<< Scala program to set and get the name of the threa...