ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

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

Problem Solution:

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

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.

Scala Threading Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.