Threading is a lightweight process. Thread creates and exists in the process with fewer resources; thread shares process resources. The main thread of Java is the thread that is launched when the program is launched.
There are two ways to set the name, either directly or indirectly, which we will be peeking through.
In Java, threads can be named using a direct method. Without providing names, threads automatically receive default names like Thread-0, Thread-1, Thread-2, and so forth. However, Java provides a couple of techniques to modify the thread name. These techniques are available in the java.lang package, specifically in the thread class.Java enables us to set the thread name at the time of thread creation rather than passing it as an argument.
import java.io.*; class ThreadName extends Thread { ThreadName(String name){ super(name); // call to constructor of thread class as super keyword of parent class } @Override public void run(){ System.out.println("Thread is running"); } } public class Main { public static void main(String args[]){ ThreadName threadName1 = new ThreadName("I Love India"); ThreadName threadName2 = new ThreadName("India is Great"); System.out.println("Thread one: " + threadName1.getName()); System.out.println("Thread two: " + threadName2.getName()); threadName1.start(); threadName2.start(); } }
Output:
Thread one: I Love India
Thread two: India is Great
Thread is running
Thread is running
By using the setName method on that thread object, we can set (modify) the thread's name. It will alter a thread's name.
import java.io.*; class ThreadName extends Thread { @Override public void run(){ System.out.println("Thread is running"); } } public class Main { public static void main(String args[]){ ThreadName threadName1 = new ThreadName(); ThreadName threadName2 = new ThreadName(); System.out.println("Thread one: " + threadName1.getName()); System.out.println("Thread two: " + threadName2.getName()); threadName1.start(); threadName2.start(); threadName1.setName("I Love India"); threadName2.setName("India is Great"); System.out.println("Changed name of thread : "); System.out.println("New Name of Thread 1 : "+ threadName1.getName()); System.out.println("New Name of Thread 2 : "+ threadName2.getName()); } }
Output:
Thread one: Thread-0
Thread two: Thread-1
Changed name of thread :
New Name of Thread 1 : I Love India
New Name of Thread 2 : India is Great
Thread is running
Thread is running
import java.io.*; class ThreadName extends Thread { @Override public void run(){ System.out.println(Thread.currentThread().getName()); } } public class Main { public static void main(String args[]){ ThreadName threadName1 = new ThreadName(); ThreadName threadName2 = new ThreadName(); threadName1.start(); threadName2.start(); threadName1.setName("I Love India"); threadName2.setName("India is Great"); } }
Output:
I Love India
India is Great
Police Colony
Patna, Bihar
India
Email:
Post your comment