Learnitweb

Thread priority and yield method

In this tutorial we’ll understand what is a thread priority. We’ll see how to get and set a thread’s priority. We’ll then look into the yield() method.

Thread priority

In JVM there is a pool of runnable threads. Thread scheduler picks one thread from the pool and provides it time to run. Different JVMs use different algorithms to pick runnable thread and run it. Most JVMs use preemptive, priority-based scheduling (sometimes called as time slicing). Thread scheduler uses thread priority while picking a thread from the pool. Thread scheduler picks up the highest priority thread to run from the pool. Low priority threads are moved back to the pool of runnable threads. Once a low priority thread is moved to the runnable pool, it can be again picked up for running.

Mostly, the running thread is equal to or has higher priority than the highest-priority thread(s) in the pool.

  • Every thread has a priority.
  • Every thread has a default priority. The default priority of a thread is same as the priority of the thread which created it.
  • Thread priority usually is a number between 1 and 10, however this is not guaranteed. 1 is the lowest and 10 is the highest priority.
  • Default priority of a thread is 5.
  • Thread class provides following constants for a thread priority.
    • Thread.MIN_PRIORITY (Thread priority 1)
    • Thread.NORM_PRIORITY (Thread priority 5)
    • Thread.MAX_PRIORITY (Thread priority 10)
  • JVM never changes a thread’s priority. However, there are methods to get and set a thread priority.

Note: Do not rely on thread priorities to design multi-threaded applications because the behavior is not guaranteed.

Example – get and set thread priority

public class ThreadPriorityExample {
	public static void main(String args[]) {
		System.out.println("Current priority of main thread: " + Thread.currentThread().getPriority());
		
		//sample message to print on console
		System.out.println("hello world");
		
		//setting priority of main thread
		Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
		System.out.println("Priority of thread after setting new priority: " + Thread.currentThread().getPriority());
	}
}

Output

Current priority of main thread: 5
hello world
Priority of thread after setting new priority: 10

yield() method

  • This method is a way to tell the scheduler that the current thread is willing to yield or give up its current use of processor.
  • The yield() method is supposed to make current running thread as runnable and allow other threads of equal priorities a chance to run. However, this behavior is not guaranteed. Once the currently running thread goes to pool of runnable threads there is no guarantee that the thread scheduler will not pick it up again. Therefore, it is not appropriate to use this method for synchronization between the threads.