Thread Scheduling and Priority in Java

来源:互联网 发布:淘宝店铺被永久封店 编辑:程序博客网 时间:2024/05/31 11:03

 Thread Scheduling and Priority

JVM implements a fixed priority thread-scheduling scheme. Each thread is assigned a priority number (between theThread.MIN_PRIORITY and Thread.MAX_PRIORITY). The higher the number, the higher is the priority for the thread. When a new thread is created, it inherits the priority number from the thread that created it. You can used the methodsetPriority() to change the priority number of a thread as follows:

public void setPriority(int priority);

The int priority is JVM dependent. It may take a value between 1 (lowest priority) to 10.

JVM chooses the highest-priority thread for execution. If there is more than one thread with the same highest-priority, JVM schedules them in a round-robin manner.

JVM also implements a pre-emptive scheduling scheme. In a pre-emptive environment, if at any time a higher priority thread becomes "runnable", the current lower priority thread will yield control to the higher priority thread immediately.

If there are more than one equal-priority runnable threads, one thread may run until the completion without yielding control to other equal-priority threads. This is known asstarvation. Therefore, it is a good practice to yield control to other equal-priority thread via thesleep() or yield() method. However, you can never yield control to a lower-priority thread.

In some operating systems such as Windows, each of the running thread is given a specific amount of CPU time. It is known as time slicing to prevent a thread from starving the other equal-priority threads. However, do not rely on time slicing, as it is implementation dependent.

Hence, a running thread will continue running until:

  • A higher priority thread becomes "runnable".
  • The running thread yields control voluntarily by calling methods such as sleep(), yield(), and wait().
  • The running thread terminates, i.e., its run() method exits.
  • On system that implements time slicing, the running thread consumes its CPU time quota.

An important point to note is the thread scheduling and priority is JVM dependent. This is natural as JVM is a virtual machine and requires the native operating system resources to support multithreading. Most JVM does not guarantee that the highest-priority thread is being run at all times. It may choose to dispatch a lower-priority thread for some reasons such as to prevent starvation. Therefore, you should not rely on the priority in your algorithm.


原创粉丝点击