Naming Thread

 

Naming Thread

The Thread class provides methods to change and get the name of a thread. By default, each thread has a name, i.e. thread-0, thread-1 and so on. By we can change the name of the thread by using the setName() method.


Example 01:

package com.java.Multi_threading;

class MyThread extends Thread {

public MyThread(String name) {

// Call the constructor of the superclass (Thread) and pass the name

super(name);

}


@Override

public void run() {

System.out.println("Thread executing: " + Thread.currentThread().getName());

}

}


public class ThreadNamingExample {

public static void main(String[] args) {

// Create threads with names

MyThread thread1 = new MyThread("Thread-A");

MyThread thread2 = new MyThread("Thread-B");


// Start the threads

thread1.start();

thread2.start();


// Print the name of the current thread

System.out.println("Main thread: " + Thread.currentThread().getName());

}

}

Post a Comment

0 Comments