Back to: Java Tutorials For Beginners and Professionals
Thread Class in Java with Examples
In this article, I am going to discuss Thread Class in Java with examples. Please read our previous article before proceeding to this article where we discussed the basics of Multithreading in Java. At the end of this article, you will understand what is Thread class, its constructors, and its methods in detail with examples.
What is Thread Class in Java?
Thread is a pre-defined class available in java.lang package which is used to create the Threads, execute the threads, and manipulate the Threads.
Constructors of Java Thread Class:
Following constructors will create the new Thread and attach with main ThreadGroup by default:
Thread t = new Thread();
Thread t = new Thread(String tname);
Thread t = new Thread(Runnable obj);
Thread t = new Thread(Runnable obj, String tname);
Following constructors will create the new Thread and attach it with user-defined ThreadGroup:
Thread t = new Thread(ThreadGroup tg);
Thread t = new Thread(ThreadGroup tg, String name);
Thread t = new Thread(ThreadGroup tg, Runnable obj);
Thread t = new Thread(ThreadGroup tg, Runnable obj, String tname);
Methods of Thread Class in Java
- Thread currentThread(): This method is used to return the information of the currently running Thread like thread name, thread priority, and thread group name to which it belongs to. This method is used to retrieve references of the currently executing thread object. This method is useful to perform some operations on a thread object when its reference is not stored in our logic.
- String getName(): This method returns the name of the particular thread, we can get the name of any thread like the main thread or user-defined thread.
- void setName(String tname): This method changes the name of the particular thread, we can change the name of any thread, it may be the main thread or user-defined thread
- int getPriority(): This method returns the priority of the particular thread, we can get the priority of any thread that is main thread or user-defined thread.
- void setPriority(int priority): This method is used to change the priority of a particular thread, we can change the priority of any thread it may be the main thread or user-defined thread.
Example to understand Methods of Thread Class in Java:
public class CurrentThreadDemo { static { System.out.println ("in static block"); //retrieving currently executing thread reference Thread th = Thread.currentThread (); System.out.println ("SB is executing in" + th.getName () + "thread"); } public static void main (String a[]) { System.out.println ("in main method"); //retrirving currently executing thread reference Thread th = Thread.currentThread (); System.out.println ("original name and priority of main thread"); System.out.println ("current thread name:" + th.getName ()); System.out.println ("current thread priority:" + th.getPriority ()); th.setName ("xxyy"); th.setPriority (7); System.out.println ("\nmodified name and priority of main thread"); System.out.println ("modified thread name:" + th.getName ()); System.out.println ("modified thread priority:" + th.getPriority ()); } }
Output:
void sleep(long ms): This method will make a particular thread wait for specified milliseconds of time. This method will throw a compile-time exception called “InterruptedException” which must be handled.
void start(): This method is used to start the execution of the thread and when we call the start() method it will perform the following two operations:
- The thread will be registered with the Thread scheduler, once the Thread gets registered with the Thread scheduler, it will provide resources required by the Thread.
- It will invoke the run() method.
Note: For a Thread, we can call the start() method at most one time because the thread doesn’t need to register with Thread Scheduler many times, otherwise, if we call the start() method for many times for a particular Thread it will throw a Runtime exception called “IllegalThreadStateException”.
ThreadGroup in Java:
Every thread is created with a thread group. The default thread group name is “main”. We can also create a user-defined thread group using the ThreadGroup class. In Thread class we have the bellow method to retrieve the current thread’s thread group object reference.
Public final ThreadGroupgetThreadGroup()
In ThreadGroup class we have the below method to retrieve the ThreadGroup name.
Public final String getName()
So in the program, we must write below statement to get Thread’s ThreadGroup name
String groupName = th.getThreadGroup().getName();
getThreadGroup(): This method returns the name of the ThreadGroup to which thread belongs to. By default, all the Threads are attached to the main ThreadGroup. We can also create our own ThreadGroup by taking the help of the ThreadGroup class.
Creation of ThreadGroup : ThreadGroup tg = new ThreadGroup(“name”);
Note: Main advantage of ThreadGroup is we can attach multiple Threads so that we can communicate with multiple Threads at a time.
Example to understand ThreadGroup in Java:
public class ThreadGroupDemo { public static void main (String[]args) { MyThread mt = new MyThread (); ThreadGroup tg = new ThreadGroup ("UDTG"); Thread t1 = new Thread (mt); Thread t2 = new Thread (tg, mt); Thread t3 = new Thread (mt); Thread t4 = new Thread (tg, mt); t1.start (); t2.start (); t3.start (); t4.start (); Thread ct = Thread.currentThread (); System.out.println (ct); } } class MyThread implements Runnable { public void run () { Thread ct = Thread.currentThread (); System.out.println (ct); } }
Output:
boolean isAlive(): This method returns true if the Thread is alive otherwise it returns false. The thread is said to be alive until it executes the run(). Once it executes the last statement in the run() method then the thread goes to the dead state.
void join(): This method makes the parent thread wait until the completion of child threads. This method also throws a compile-time exception called InterruptedException which must be handled.
Example to demonstrate Join() method of Thread class in java
public class Main { public static void main (String[]args) { System.out.println ("Main Thread started..."); MyThread1 mt1 = new MyThread1 (10); MyThread1 mt2 = new MyThread1 (15); Thread t1 = new Thread (mt1, "child1"); Thread t2 = new Thread (mt2, "child2"); t1.start (); t2.start (); for (int i = 1; i <= 5; i++) { System.out.println ("Main Thread Value:" + i); try { Thread.sleep (1000); } catch (InterruptedException ie) { } } System.out.println (t1.isAlive ()); //true System.out.println (t2.isAlive ()); //true try { t1.join (); t2.join (); } catch (InterruptedException ie) { } System.out.println (t1.isAlive ()); //false System.out.println (t2.isAlive ()); //false System.out.println ("Main thread is terminated..."); } } class MyThread1 implements Runnable { int n; MyThread1 (int n) { this.n = n; } public void run() { Thread t = Thread.currentThread ();; System.out.println (t.getName () + "Thread started..."); for (int i = 1; i <= n; i++) { System.out.println (t.getName () + "Thread value:" + i); try { Thread.sleep (1000); } catch (InterruptedException ie) { } } System.out.println (t.getName () + "Thread is Terminated..."); } }
Types of Threads in Java:
Java allows us to create two types of threads, they are
- Non-daemon threads
- Daemon threads
A thread that executes the main logic of the project is called a non-daemon thread. A thread that is running in the background to provide services to non-daemon threads is called a daemon thread. So we can say daemon threads are service threads. Since daemon threads are service threads, their execution is terminated if all non-daemon threads’ execution is completed.
Every user-defined thread is created as a non-daemon thread by default because the main thread is a non-daemon thread and the daemon property is also inherited from the parent thread. The garbage collector is a daemon thread. Since garbage collector provides service- destroying unreferenced objects.
Daemon thread creation in Java:
To create a user-defined thread as a daemon thread, the thread class has the below method
void setDaemon(Boolean on): This method is used to change the threads as daemon threads or non-daemon threads. If on value is true thread is created as daemon else it is created as a non-daemon thread. The daemon property default value is false.
To check thread is daemon or non-daemon, the thread class has the below method
Boolean isDaemon(): This method returns true if the particular Thread is Daemon Thread otherwise it returns false.
Note: setDaemon method cannot be called after start() method call, it leads to RE: java.lang.illegalThreadStateException. because once the thread is created as a non-daemon thread, it cannot be converted as a daemon.
Example: Daemon thread in Java
public class DaemonDemo implements Runnable { Thread th; DaemonDemo () { th = new Thread (this); th.setDaemon (true); th.start (); //th.setDaemon(true); } public void run () { System.out.println ("Run:" + th.isDaemon ()); for (int i = 1; i <= 100; i++) { System.out.println ("Run :" + i); } } public static void main (String args[]) { DaemonDemo dd1 = new DaemonDemo (); System.out.println ("countdown starts"); for (int i = 1; i <= 5; i++) { System.out.println ("main :" + i); } } }
Output: daemon thread execution is terminated in the middle, all iterations output will not be printed.
- static void yield(): It causes the current thread to halt and other threads to execute.
- void run(): It is used to do an action for a thread.
- void stop(): It is used to stop the thread.
In the next article, I am going to discuss the Thread Life Cycle in Java with examples. Here, in this article, I try to explain Thread Class in Java with examples. I hope you enjoy this Java Thread Class with Examples article.