Threads always run with some priority, usually represented as a number between 1 and 10 (although in some cases the range is less than 10). A thread gets a default priority that is the priority of the thread of execution that creates it.
But, you can also set a thread’s priority directly by calling the setPriority()
method on a Thread
instance. One thing to remember about thread priorities is never rely on thread priorities, because thread-scheduling priority behavior is not guaranteed.
package org.kodejava.lang;
public class ThreadPriority extends Thread {
private final String threadName;
ThreadPriority(String threadName) {
this.threadName = threadName;
}
public static void main(String[] args) {
ThreadPriority thread1 = new ThreadPriority("First");
ThreadPriority thread2 = new ThreadPriority("Second");
ThreadPriority thread3 = new ThreadPriority("Third");
ThreadPriority thread4 = new ThreadPriority("Fourth");
ThreadPriority thread5 = new ThreadPriority("Fifth");
// set thread1 to minimum priority = 1
thread1.setPriority(Thread.MIN_PRIORITY);
// set thread2 to priority 2
thread2.setPriority(2);
// set thread3 to normal priority = 5
thread3.setPriority(Thread.NORM_PRIORITY);
// set thread4 to priority 8
thread4.setPriority(8);
// set thread5 to maximum priority = 10
thread5.setPriority(Thread.MAX_PRIORITY);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
}
@Override
public void run() {
System.out.println("Running [" + threadName + "]");
for (int i = 1; i <= 10; i++) {
System.out.println("[" + threadName + "] => " + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024