In Java, threads are scheduled by the operating system to run on the CPU. The Java Thread scheduler uses a priority-based scheduling algorithm to determine which threads should be given CPU time. The thread priority determines the order in which threads are scheduled to run by the thread scheduler.
In Java, thread priorities are represented by integer values ranging from 1 to 10, with 1 being the lowest priority and 10 being the highest priority. By default, all threads are given priority 5. A thread's priority can be set using the setPriority() method, which is defined in the Thread class.
Here's an example to illustrate how to set thread priorities in Java:
class MyThread implements Runnable {
public void run() {
System.out.println(Thread.currentThread().getName() + " running with priority " + Thread.currentThread().getPriority());
}
}
public class ThreadPriorityExample {
public static void main(String[] args) {
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();
thread1.setPriority(Thread.MIN_PRIORITY);
thread2.setPriority(Thread.MAX_PRIORITY);
Thread t1 = new Thread(thread1);
Thread t2 = new Thread(thread2);
t1.start();
t2.start();
}
}
In this example, we have a MyThread class that implements the Runnable interface. The run() method of MyThread simply prints the name of the thread and its priority.
In the main() method, we create two instances of MyThread. We set the priority of thread1 to the minimum priority using the setPriority() method and set the priority of thread2 to the maximum priority. We then create two Thread objects t1 and t2, passing in thread1 and thread2 as arguments. We start both threads using the start() method.
When we run this program, we'll see that thread1 runs with priority 1 and thread2 runs with priority 10. The output of the program will be something like:
Thread-0 running with priority 1
Thread-1 running with priority 10
Note that thread priorities are only a hint to the Java Thread scheduler, and the actual behavior of the scheduler may depend on the underlying operating system. In general, higher-priority threads are given more CPU time than lower-priority threads, but this is not guaranteed. Also, thread priorities should be used with caution, as setting thread priorities too high can starve other threads of CPU time and lead to poor performance.