Middle — Middle+
How can you ensure the execution of a thread with higher priority in a multithreaded environment?
sobes.tech AI
Answer from AI
In Java, to set thread priority, the method setPriority(int newPriority) of the Thread class is used. Priority influences the thread scheduler, allowing more CPU time to threads with higher priority.
Important points:
- Priorities are set in the range from
Thread.MIN_PRIORITY(1) toThread.MAX_PRIORITY(10), with the default beingThread.NORM_PRIORITY(5). - Setting a higher priority does not guarantee immediate execution but increases the chances of getting CPU time.
- Thread scheduling depends on the OS and JVM, so behavior may vary.
Example:
Thread highPriorityThread = new Thread(() -> {
// thread code
});
highPriorityThread.setPriority(Thread.MAX_PRIORITY);
highPriorityThread.start();