Thread Priorities

  • Properties are integer values which is range from 1 to 9.
  • 1 indicates lowest priority and 9 indicate highest priority.
  • Thus, when we have multiple threads in wait state and if we call notify () in the current thread, then the thread with highest priority will be notified first.
  • Priorities should be assigned to the corresponding threads before calling the start () method.
  • To assign the priorities to threads, we use the set priority () method. It is a non-static function which accepts an integer value (1 to 9) as an argument.
  • Priority concept can be used only when there is possibility for threads to enter the wait state.

Consider the following scenarios:

t1, t2, t3 --------- threads

t1. Set priority (4);

t2. Set priority (9);

t3. Set priority (7);

Running state                     wait state t1, t2

t3

Run ()

{

Notify ();   which thread will it notify?

Explanation:

  • We have three threads t1, t2 and t3 and their priorities are set as shown above.
  • Let us assume that t1 and t2 are in wait state and t3 is running state.
  • Now, if notify () is encountered in the run () method of t3 then it obviously notifies t2 because, t2 has highest priority.
  • If we don’t set a priority to a thread explicitly, then every thread will have a default priority. The default priority is none other than the priority of the parent thread from which the current thread is spawned.
  • As an absolute value, a priority is meaningless: a higher priority thread does not run any faster than lowest priority thread if it is the only thread running.
  • Instead, a threads priority is used to decide when to switch from one running thread to the next. This is called a context switch.

The rules are determined a context switch is simple: 

  1. A thread can voluntarily relinquish control. In these scenarios, all other threads are examined, and the highest priority thread that is really to run given the CPU time.
  2. A thread can be preempted by a highest priority thread that does not yield the processor is simply preempted by the highest priority thread. Basically as soon as a highest priority thread wants to run, it does. This is called preemptive multitasking.

Thread Priorities Homework Help