What’s the Java Thread Class?


Developer.com content material and product suggestions are editorially impartial. We could earn money once you click on on hyperlinks to our companions. Study Extra.

In our Java concurrency tutorial, we realized that the Thread class is the primary class upon which Java’s multithreading system relies. It, together with the Runnable interface are what make multithreading potential in Java. Though builders can implement the Runnable interface to run a chunk of code a separate thread, there may be actually no requirement to take action, because the Thread class already implements it. Furthermore, it gives a number of constructors and strategies to help multithreading. In at present’s programming tutorial, we shall be exploring how one can use the Thread class’s constructors and strategies in our Java purposes.

Take a look at our earlier article on Java Concurrency for extra.

Java Thread Class Constructors

As you may think, conserving tabs on your whole lively threads is usually a daunting process. For that purpose, Java’s Thread class comes outfitted with a number of constructors that will let you identify your Threads and even assign them to teams. Java’s Thread class constructors embrace:

  1. Thread()
  2. Thread(String identify)
  3. Thread(Runnable r)
  4. Thread(Runnable r, String identify)
  5. Thread(ThreadGroup group, Runnable goal)
  6. Thread(ThreadGroup group, Runnable goal, String identify)
  7. Thread(ThreadGroup group, Runnable goal, String identify, lengthy stackSize)
  8. Thread(ThreadGroup group, String identify)

Right here is an instance Java Program illustrating how one can set the identify of a thread at time of creation. It additionally refers back to the thread’s identify contained in the run() methodology:

import java.io.*;

class ThreadNamingExample extends Thread {
  
  // The subclass should additionally embrace the constructor
  // to be able to use it  
  ThreadNamingExample(String identify) {
    // Name the Thread class constructor
    tremendous(identify);
  }
  
  @Override 
  public void run() {
    System.out.println(this.getName() + " is operating.....");
  }
  
  public static void essential(String[] args) {
    
    // Create two threads
    ThreadNamingExample t1 = new ThreadNamingExample("Thread 1");
    ThreadNamingExample t2 = new ThreadNamingExample("Thread 2");
    
    // Get the above created threads' names.
    System.out.println(t1.getName() + " has began.");
    System.out.println(t2.getName() + " has began.");
    
    // Beginning threads utilizing begin() methodology
    t1.begin();
    t2.begin();
  }
}

We will see this system together with its produced output under:

Java Thread tutorial

It’s price mentioning that there’s additionally a setName() methodology, so you may replace a Thread’s identify at any time.

Learn: IntelliJ IDEA Overview

Tips on how to Fetch the Title of the Present Thread in Java

Within the above code instance, we referred to as the category’s getName() methodology instantly by way of the this pointer. One other strategy to get hold of a reference to the lively thread identify is to invoke the static Thread.currentThread() methodology. We might then name getName() on the returned thread:

@Override 
public void run() {
  System.out.println(Thread.currentThread().getName() + " is operating.....");
}

The Thread Lifecycle in Java

Now that now we have lined some Thread fundamentals, this is likely to be time to go over the lifecycle of a thread and it’s many states. The next diagram exhibits the completely different states concerned within the life cycle of a thread.

Java Thread Lifecycle

 

Because the above diagram exhibits, a thread at all times exists in any one of many following 5 states:

  1. New
  2. Lively
  3. Blocked / Ready
  4. Timed Ready
  5. Terminated

Programmers can get a thread’s present state at any time by invoking the getState() methodology. Here’s a Java code instance that employs it to point out among the thread states outlined above:

public class ThreadStateDemo extends Thread {
	public static Thread t1;  
	public static ThreadStateDemo threadStateDemo;  
	
	class Thread2 extends Thread {  
		public void run() {    
		  
			attempt {  
				// transfer thread t2 to the state timed ready  
				Thread.sleep(100);  
			}  
			catch (InterruptedException ie) {  
				ie.printStackTrace();  
			}  
			  
			System.out.println(
				"The state of thread t1 whereas it invoked the tactic be a part of() on thread t2 -"
				+ t1.getState()
			);  
			   
			attempt {  
				Thread.sleep(200);  
			}  
			catch (InterruptedException ie) {  
				ie.printStackTrace();  
			}     
		}  
	}  
	
	public static void essential(String[] args) {
		threadStateDemo = new ThreadStateDemo();  
		t1 = new Thread(threadStateDemo);  
		  
		// thread t1 is spawned   
		// The thread t1 is at present within the NEW state.  
		System.out.println("The state of thread t1 after spawning it - " + t1.getState());  
		  
		// invoke the beginning() methodology on the thread t1  
		t1.begin();  
		  
		// thread t1 is moved to the Runnable state  
		System.out.println(
		  "The state of thread t1 after invoking the tactic begin() on it - " 
		  + t1.getState()
		);  
	}

	public void run() {  
		Thread2 thread2 = new Thread2();  
		Thread t2 = new Thread(thread2);  
		  
		// thread t2 is created and is at present within the NEW state.  
		System.out.println("The state of thread t2 after spawning it - "+ t2.getState());  
		t2.begin();  
		  
		// thread t2 is moved to the runnable state  
		System.out.println(
			"the state of thread t2 after calling the tactic begin() on it - " 
			+ t2.getState()
		);  
		  
		attempt {  
			// transfer the thread t1 to the state timed ready   
			Thread.sleep(200);  
		}  
		catch (InterruptedException ie) {  
			ie.printStackTrace();  
		}  
		  
		System.out.println(
			"The state of thread t2 after invoking the tactic sleep() on it - "
			+ t2.getState()
		);  
		   
		attempt {  
			// anticipate thread t2 to finish its execution  
			t2.be a part of();  
		}  
		catch (InterruptedException ie) {  
			ie.printStackTrace();  
		}  
		System.out.println(
			"The state of thread t2 when it has accomplished it is execution - " 
			+ t2.getState()
		);  
	}  
}

Working this system prints the next output to the console:

The state of thread t1 after spawning it - NEW
The state of thread t1 after invoking the tactic begin() on it - RUNNABLE
The state of thread t2 after spawning it - NEW
the state of thread t2 after calling the tactic begin() on it - RUNNABLE
The state of thread t1 whereas it invoked the tactic be a part of() on thread t2 -TIMED_WAITING
The state of thread t2 after invoking the tactic sleep() on it - TIMED_WAITING
The state of thread t2 when it has accomplished it is execution - TERMINATED

The above program additionally showcased the be a part of() methodology, which waits for the calling thread to finish its execution. That’s the reason the following name to getState() returned a Thread.State enum worth of TERMINATED.

Learn: Prime Java Frameworks

Ultimate Ideas on the Java Thread Class

On this follow-up to the Java concurrency tutorial, we realized how one can use the Thread class’s many constructors and strategies in our Java purposes. With just a little underneath forty strategies, there may be much more to the Thread class than lined right here. You possibly can see the total itemizing within the official docs.

Latest articles

Related articles

Leave a reply

Please enter your comment!
Please enter your name here