Thread
Priority
Thread priority is a mechanism used in operating systems to determine the order in which threads are executed. It influences how much CPU time a thread receives relative to other threads.
•
Each thread has a priority.
•
Priorities are represented by a number
between 1 and 10.
3 constants defined in Thread class:
public static int MIN_PRIORITY
public static int NORM_PRIORITY
public static int MAX_PRIORITY
Default priority of a thread is 5
(NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of MAX_PRIORITY
is 10.
Example 01:
package com.java.Multi_threading;
class PriorityExample {
public static void main(String[] args) {
Thread thread1 = new Thread(new MyRunnable(), "Thread 1");
Thread thread2 = new Thread(new MyRunnable(), "Thread 2");
// Set priorities
thread1.setPriority(Thread.MIN_PRIORITY);
thread2.setPriority(Thread.MAX_PRIORITY);
// Start the threads
thread1.start();
thread2.start();
}
}
class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " - Count: " + i);
Thread.yield(); // Allowing the scheduler to switch between threads
}
}
}
0 Comments