Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prioritization of threads within threads

Suppose you have a program that starts two threads a and b, and b starts another ten threads of its own. Does a receive half of the available "attention" while b and its threads share the other half, or do they all share equally? If the answer is the latter by default, how could you achieve the former? Thanks!

like image 246
wheels Avatar asked Apr 30 '13 10:04

wheels


1 Answers

There are lots of nice documentation on this topic. One such is this.

When a Java thread is created, it inherits its priority from the thread that created it. You can also modify a thread's priority at any time after its creation using the setPriority() method. Thread priorities are integers ranging between MIN_PRIORITY and MAX_PRIORITY (constants defined in the Thread class). The higher the integer, the higher the priority. At any given time, when multiple threads are ready to be executed, the runtime system chooses the "Runnable" thread with the highest priority for execution. Only when that thread stops, yields, or becomes "Not Runnable" for some reason will a lower priority thread start executing. If two threads of the same priority are waiting for the CPU, the scheduler chooses one of them to run in a round-robin fashion. The chosen thread will run until one of the following conditions is true:

  1. A higher priority thread becomes "Runnable".
  2. It yields, or its run() method exits.
  3. On systems that support time-slicing, its time allotment has expired.

At any given time, the highest priority thread is running. However, this is not guaranteed. The thread scheduler may choose to run a lower priority thread to avoid starvation. For this reason, use priority only to affect scheduling policy for efficiency purposes. Do not rely on thread priority for algorithm correctness.

like image 193
AllTooSir Avatar answered Oct 31 '22 00:10

AllTooSir