2024. 10. 20. 14:16ㆍJAVA & SPRING/자바
What is Thread Priority?
The priority in the order of execution that the operating system assigns to each thread when scheduling threads. Threads with a higher priority are executed before threads with a lower priority.
The default thread priority in Java is 5, and you can specify the priority of thread execution in the range 1 to 10.
Generally, threads with higher priorities will have a higher chance of being executed than threads with lower priorities. We can use the setPriority() method of the Thread class to set the priority of a thread.
The reason for not recommending to use the thread priority
It is not advised to set the thread priority because the operating system's thread scheduling algorithm determines the actual order of execution. Therefore, a result of multiple threads set priorities can be different from what you expected.
// This priority setting is really not reliable since the result is not same as expected(t3 -> t2 -> t1)
public class TestExecuteOrder {
static class MyRunnable implements Runnable {
@Override
public void run() {
System.out.printf("The currently executing thread is :%s, priority:%s",
Thread.currentThread().getName(), Thread.currentThread().getPriority() + "\n");
}
}
public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable());
t1.setPriority(1);
Thread t2 = new Thread(new MyRunnable());
t2.setPriority(5);
Thread t3 = new Thread(new MyRunnable());
t3.setPriority(10);
t3.start();
t2.start();
t1.start();
}
}
Result
The currently executing thread is :Thread-2, priority:10
The currently executing thread is :Thread-0, priority:1
The currently executing thread is :Thread-1, priority:5
If the priority of a thread is different from that of its thread group?
The thread's priority will be invalidated and replaced with the maximum priority of the thread group.
public class ThreadGroupOrder {
public static void main(String[] args) {
ThreadGroup myThreadGroup = new ThreadGroup("myThreadGroup");
myThreadGroup.setMaxPriority(6);
Thread myThread = new Thread(myThreadGroup, "myThread");
myThread.setPriority(8);
System.out.println("myThreadGroup = " + myThreadGroup.getMaxPriority());
System.out.println("myThread = " + myThread.getPriority());
}
}
Result
myThreadGroup = 6
myThread = 6
'JAVA & SPRING > 자바' 카테고리의 다른 글
| Java Concurrency - Thread Safe (1) | 2024.10.27 |
|---|---|
| Java Concurrency - stop(), interrupt() (0) | 2024.10.26 |
| Java Concurrency - Thread Group (1) | 2024.10.19 |
| Java Concurrency - wait / notify / notifyAll / sleep (1) | 2024.10.15 |
| AtomicInteger, Concurrent Collections 알아보기 (1) | 2024.08.27 |