Thread priority and runnable Interface
Thread priority and runnable Interface
Thread Priority
In Java, each thread is assigned a priority, which is typically represented as a number ranging from 1 to 10. While the thread scheduler often schedules threads based on their priorities, it's important to note that this behavior is not guaranteed. The specific scheduling mechanism employed can vary depending on the JVM implementation and may not strictly follow priority-based scheduling. Additionally, Java programmers have the ability to explicitly set the priorities of threads within their Java programs, offering some control over thread execution
In the context of threads, priorities refer to a concept where each thread is assigned a priority value, which can be thought of as a sort of importance level.
These priorities are represented by numbers ranging from 1 to 10.
The default priority is typically set to 5.
The lowest possible priority is 1.
The highest priority a thread can have is 10
In Java, there are three constants defined for thread priorities:
NORM_PRIORITY: This constant represents the normal priority level for threads.
MIN_PRIORITY: It stands for the minimum (lowest) priority value a thread can have.
MAX_PRIORITY: This constant represents the maximum (highest) priority value that a thread can be assigned.
To further illustrate these concepts, let's delve into an example that demonstrates how they work internally based on the knowledge we've gathered so far
We will utilize the currentThread() method to retrieve the name of the current thread. Additionally, users have the option to use the setName() method if they wish to assign custom names to threads for better comprehension. To obtain the name of a thread, we will employ the getName() method.
Let's explore how to access and modify the priority of a thread in Java. We can do this using the following methods:
public final int getPriority(): The getPriority method in the java.lang.Thread class retrieves the priority of a given thread.
public final void setPriority(int newPriority): The setPriority method in the java.lang.Thread class allows you to change the priority of a thread to a new value specified by newPriority. It's important to note that this method will throw an IllegalArgumentException if the newPriority value exceeds the limits of the minimum (1) and maximum (10) priority values
Example:-
// Importing required classes
import java.lang.*;
// Main class
class ThreadDemo extends Thread {
// Method 1
// run() method for the thread that is called
// as soon as start() is invoked for thread in main()
public void run()
{
// Print statement
System.out.println("Inside run method");
}
// Main driver method
public static void main(String[] args)
{
// Creating random threads
// with the help of above class
ThreadDemo t1 = new ThreadDemo();
ThreadDemo t2 = new ThreadDemo();
ThreadDemo t3 = new ThreadDemo();
// Thread 1
// Display the priority of above thread
// using getPriority() method
System.out.println("t1 thread priority : "
+ t1.getPriority());
// Thread 1
// Display the priority of above thread
System.out.println("t2 thread priority : "
+ t2.getPriority());
// Thread 3
System.out.println("t3 thread priority : "
+ t3.getPriority());
// Setting priorities of above threads by
// passing integer arguments
t1.setPriority(3);
t2.setPriority(6);
t3.setPriority(7);
// t3.setPriority(21); will throw
// IllegalArgumentException
// 3
System.out.println("t1 thread priority : "
+ t1.getPriority());
// 6
System.out.println("t2 thread priority : "
+ t2.getPriority());
// 7
System.out.println("t3 thread priority : "
+ t3.getPriority());
// Main thread
// Displays the name of
// currently executing Thread
System.out.println(
"Currently Executing Thread : "
+ Thread.currentThread().getName());
System.out.println(
"Main thread priority : "
+ Thread.currentThread().getPriority());
// Main thread priority is set to 10
Thread.currentThread().setPriority(10);
System.out.println(
"Main thread priority : "
+ Thread.currentThread().getPriority());
}
}
Output:-
t1 thread priority : 5
t2 thread priority : 5
t3 thread priority : 5
t1 thread priority : 3
t2 thread priority : 6
t3 thread priority : 7
Currently Executing Thread : main
Main thread priority : 5
Main thread priority : 10
Java Runnable Interface
The Runnable interface in Java serves as a blueprint for executing code on a concurrent thread. Any class can implement this interface to enable instances of that class to be executed by a thread.
The Runnable interface defines a single method, run(), which has a void return type and takes no arguments. This method is where the code to be executed concurrently is placed.
Certainly, here's a paraphrased version of your explanation
Begin by creating a class that implements the Runnable interface. Within this class, you must provide an implementation for the run() method, which contains the code you want to execute concurrently in a new thread.
After implementing the Runnable interface, you'll need to instantiate an object of this class. This instance represents the task you want to run in a separate thread.
Next, create an instance of the Thread class, which is responsible for managing and executing threads. The Thread class has a constructor that accepts a Runnable instance. Pass your Runnable instance to this constructor to associate your task with the new thread.
To initiate the execution of the task in the new thread, you should call the start() method on the Thread instance. The start() method internally triggers the execution of the run() method of the Runnable instance provided. Importantly, using start() creates a new thread of execution, whereas directly calling run() will execute the code in the current thread, not a new one. To ensure parallel execution, use start() to initiate the new thread.
Here's a simple example of how to use the Runnable interface to create and start a thread in Java:
public class Demo {
public static void main(String[] args)
{
System.out.println("Main thread is- "
+ Thread.currentThread().getName());
Thread t1 = new Thread(new RunnableDemo().new RunnableImpl());
t1.start();
}
private class RunnableImpl implements Runnable {
public void run()
{
System.out.println(Thread.currentThread().getName()
+ ", executing run() method!");
}
}
}
In this example: -
We create a class MyRunnable that implements the Runnable interface.
Inside the run() method, we define the task to be executed by the thread.
In the main method, we create an instance of MyRunnable.
We create a Thread object and pass our MyRunnable instance to it.
Finally, we start the thread using the start() method.
When you run this program, it will create a new thread and execute the run() method concurrently with the main thread.
Using the Runnable interface is just one way to work with threads in Java. Java also provides the Thread class itself, which you can extend to create threads, but implementing Runnable is often preferred because it allows better separation of the task's logic from the threading mechanism.