Thread class in java

the Thread class in java is the most important part of multithreading. We can create a thread in two ways whether to use the Thread class or the Runnable interface. In this post, we will see what is Thread class in java and how it is useful in multithreading?

Thread class in java

Here is the table content of the article will we will cover this topic.
1. What is the thread class in java?
2. How Thread class is useful?
3. Constructors of Thread class
4. Methods of Thread class

What is the thread class in java?

The Thread class in java is present in java.lang package. The Thread class extends the Object class and implements the Runnable interface. As we know we can create threads by use of the Thread class and achieve multithreading. The Thread class in java provides constructors and methods to create and perform operations on a thread.

How Thread class is useful

The Thread class has various methods that are useful to handle the execution of the thread. A program can have multiple threads and each thread has some properties. The thread scheduler uses the priority of the thread to handle it. The Thread scheduler uses the priority of threads and determines which thread must run first. Java provides a Thread class that has various methods that can manage the order and behavior of threads. In the below section, we will discuss some important constructors and methods.

Constructors of Thread class

  • Thread(): It is the default constructor of the Thread class. It is used to create an object of the Thread class.
  • Thread(Runnable target): It is a parameterized constructor of the Thread class which takes a parameter of Runnable. It creates an object like a default constructor (Thread()). The parameter target is the object whose run() method is invoked when the start gets the call().
  • Thread(Runnable target, String name): It is parameterized constructor that is used to create an object of the Thread class. It takes two parameters one is the Runnable type and another String type. It is similar to the above-mentioned constructor except you can set the name of the thread.
  • Thread(String name): It is a parameterized constructor that is used to create an object of the Thread class. It takes only one parameter of String type. You can set the name of the thread to pass the parameter
  • Thread(ThreadGroup group, Runnable target): It is a parameterized constructor that is used to create an object of the Thread class. It takes two parameters one is the ThreadGroup type and another Runnable type. The group parameter is a collection of multiple threads into a single object and the target is the object whose run() method is invoked when the start gets the call().

Thread(ThreadGroup group, Runnable target, String name): The parameterized constructor that uses to create an object of the Thread class. It takes three parameters first one is the ThreadGroup type, second is the Runnable type and third is a String type. ThreadGroup group parameter is a collection of multiple threads into a single object.
The Runnable target parameter reference of Runnable
String name parameter, the name of the thread.

  • Thread(ThreadGroup group, String name): It is a parameterized constructor that is used to create an object of the Thread class. It takes two parameters first one is the ThreadGroup type and the second is the String type. ThreadGroup group parameter is a collection of multiple threads into a single object. String name parameter is used to set the name of the thread.
  • Thread(ThreadGroup group, Runnable target, String name, long stackSize): It is a parametrized constructor that is used to create an object of the Thread class. It takes three parameters first one is the ThreadGroup type, second is the Runnable type and third is a String type. ThreadGroup group parameter is a collection of multiple threads into a single object. The runnable target parameter is the object whose run() method is invoked when the start get the call().
    String name, the parameter is used to set the name of the thread.
    long stackSize, the desired stack size for the new thread, or zero to indicate that this parameter is to be ignored.

Methods of Thread class

The Thread class has many methods those uses to perform some operations on the thread. We can change the order and behaviors of threads by the use of methods.

  1. start(): This method is used to start the execution of the thread. It is very frequently used in multithreading. For more detail, you can visit here.
  2. run(): This method performs the action for a thread. It gets a call from the start() method. For more detail, you can visit here.
  3. sleep(): It is used to sleep the current thread for a specific time. For more detail, you can visit here.
  4. yield(): The yield() method is used to give the hint to the thread scheduler. If the current thread is not doing anything important and any other threads need to be run, they should run. Otherwise, the current thread will continue to run. For more detail, you can visit here.
  5. join(): The join() method belongs to Thread class. The join() method is used when we want one thread to wait until another thread completes its execution. For more detail, you can visit here.

Some more methods of thread class

  1. getName(): This method returns the name of the thread. It is a public and final method. Its return type is String. For more detail, you can visit here.
  2. setName(String name): This method is used to set the name of the thread. It is a public, final and synchronized method. Its return type is void which means it doesn’t return anything. For more detail, you can visit here.
  3. isDaemon(): This method returns a boolean value either true or false. This method is used to check whether the thread is a daemon thread or not. It is a public and final method. Its return type is boolean. For more detail, you can visit here.
  4. setDaemon (boolean on): This method is used to set a thread as a daemon thread. You can mark any user thread as a daemon thread bypassing the value true (setDaemon(true)) in a parameter. If I have a Daemon thread and you can make it a user thread bypassing the value false setDaemon(false)). For more detail, you can visit here.
  5. getPriority(): This method returns the priority of the thread. It is a public and final method. Its return type is int. For more detail, you can visit here.
  6. setPriority(int newPriority): This method is used to set the priority of a thread. Its return type is void it means it doesn’t return anything.  For more detail, you can visit here.

Methods of Thread class

Thread priority in java

Each thread has a priority and that helps the thread scheduler decide which thread should start first. Whenever we create a thread it automatically inherits the priority from the parent thread. We will learn what is thread priority in java and how we can set and get the priority of the thread.

What is thread priority in java?

As we know each program has at least one thread to run the program. Each thread has a priority and by default, JVM assigns it to every thread. Whenever we create a thread it inherits the priority from its parent thread. But we can also assign the priority to the thread by the setPriority() method.

1. A thread can have priority in the range of 1 to 10. The thread class provides the 3 static variables defined in the Thread class for priority.

public static final int MIN_PRIORITY = 1;
public static final int NORM_PRIORITY = 5;
public static final int MAX_PRIORITY = 10;

2. The JVM assigns NORM_PRIORITY to the main thread by default. When a thread creates from the main thread it automatically inherits its priority.

3. We can modify the priority of the thread after creation by using of setPriority() method.

4. The higher integer value means that it has a higher priority. In real-time we give higher priority to the thread if it is a critical thread and needs to execute first.

5. The thread scheduler pick first those threads that have a higher priority from the RUNNABLE queue. If two threads of the same priority are waiting for the CPU, the scheduler chooses one of them to run in a round-robin fashion

Importance of thread priority

In multithreading, each thread has a priority that helps the thread scheduler to determine the order of execution. Higher-priority threads execute first.

Let’s say we have three threads thread1, thread2, and thread3 and they have priority 5, 6, and 10 respectively. If all three threads are in a runnable state and waiting for the CPU cycle. Then there is more chance thread3 gets the CPU first because its priority is high. But it is always not true because the thread scheduler decides the execution of threads based on some criteria.

How to set the priority and get the priority?

The default priority of thread is 5. You can set the priority of a thread in the range of 1 to 10. Thread class has three variables to set priority.

  1. public static int MIN_PRIORITY
  2. public static int NORM_PRIORITY
  3. public static int MAX_PRIORITY

1. public static int MIN_PRIORITY:  This is the minimum priority value that can hold a thread. The value for this is 1.
2. public static int NORM_PRIORITY: The default priority of a thread that assigns by JVM. I do not explicitly define it. The value for this is 5.
3. public static int MAX_PRIORITY: This is the maximum priority of a thread. The value for this is 10.

We can check the priority of the thread and modify it. Thread class provides two methods for priority.

1. public final int getPriority(): This method returns the priority of the thread. It is a public and final method. Its return type is int.

2. public final void setPriority(int newPriority): To set the priority of the thread we use this method. It is a public and final method. Its return type is void which means it doesn’t return anything.
newPriority: This method takes only one parameter of int type. A programmer can assign new priority to the thread by providing an integer value in the parameter. The integer value must be between 1 to 10. If the value of the parameter doesn’t lie between 1 to 10 it will throw IllegalArgumentException.

public class ExampleOfPriority extends Thread 
{

	public static void main(String[] args)
        {
		ExampleOfPriority thread1 = new ExampleOfPriority(); 
		ExampleOfPriority thread2 = new ExampleOfPriority(); 
		ExampleOfPriority thread3 = new ExampleOfPriority(); 
  
      System.out.println("The priority of thread1 = " + thread1.getPriority()); // Default 5 
      System.out.println("The priority of thread2 = " + thread2.getPriority()); // Default 5 
      System.out.println("The priority of thread3 = " + thread3.getPriority()); // Default 5 
        
        thread1.setPriority(6); 
        thread2.setPriority(7); 
        thread3.setPriority(8); 
       
        System.out.println("The priority of thread1 = " + thread1.getPriority()); 
        System.out.println("The priority of thread2 = " + thread2.getPriority());  
        System.out.println("The priority of thread3 = " + thread3.getPriority());  
  
        // Main thread 
        System.out.println("The priority of Main thread = " + 
        Thread.currentThread().getPriority()); 
  
        // Main thread priority is set to 10 
        Thread.currentThread().setPriority(10); 
        
        // Main thread 
        System.out.println("The priority of Main thread = " + 
       Thread.currentThread().getPriority()); 

	}
}

Output:
The priority of thread1 = 5
The priority of thread2 = 5
The priority of thread3 = 5
The priority of thread1 = 6
The priority of thread2 = 7
The priority of thread3 = 8
The priority of Main thread = 5
The priority of Main thread = 10

Naming a thread in java

In a java program, each thread has a name that is automatically provided by JVM. We can also set the Naming a thread in java by calling the setName() method. JVM by default provides the name to the thread but a programmer can also provide the name. By default, each thread has a name i.e. thread-0, thread-1, and so on.

Importance of Naming a thread in java

In a Multi-threading environment, multiple threads are working at the same time. Sometimes multiple threads execute the same code or the same lines of code and we want to know which thread is executing the line of code. So, we can check this to get the name of the thread that provides ease for the programmer. 

We can set and get the name of the thread. Thread class provides two methods for name:

1. public final String getName()

2. public final synchronized void setName(String name)

1. public final String getName(): This method returns the name of the thread. It is a public and final method. Its return type is String.

2. public final synchronized void setName(String name): The programmer uses this method to set the name of the thread. It is a public, final, and synchronized method. Its return type is void it means it doesn’t return anything.
name: This method takes only one parameter of String type. A programmer can assign a new name to a thread.

Example of java thread setName() and getName()

Let’s say we have three threads thread1, thread2, and thread3. If all three threads are in RUNNABLE state and printing the counting of numbers. Here we want to know which thread is printing the counting of numbers at a time. So, we can use the setName() method to set the name and getName() method to get the name of the thread.

public class ExampleOfNaming extends Thread 
{		
   public void run()
   {  
	for(int i = 1; i <= 5; i++)
	{  
           System.out.println(Thread.currentThread().getName() + " is running 
           and value of i = "+i);  
	}  
   }  
   public static void main(String args[])
   {  
	 ExampleOfJoinMethod thread1 = new ExampleOfJoinMethod();  
	 thread1.setName("Thread1");
	 ExampleOfJoinMethod thread2 = new ExampleOfJoinMethod();
	 thread2.setName("Thread2");
		 
	 thread1.start();  
				
	 thread2.start();  
   }  
}

Output:
Thread1 is running and value of i = 1
Thread2 is running and value of i = 1
Thread1 is running and value of i = 2
Thread2 is running and value of i = 2
Thread1 is running and value of i = 3
Thread2 is running and value of i = 3
Thread2 is running and value of i = 4
Thread1 is running and value of i = 4
Thread2 is running and value of i = 5
Thread1 is running and value of i = 5

Leave a Comment