Saturday, 27 June 2015

Thread priorities - Java multithreading

When we talk about thread we use terms like concurrent threads or threads executing concurrently. But in reality threads also run one at a time (at least in a single CPU system), threads are given CPU cycle in a time shared manner to simulate concurrency.
The order in which multiple threads will be executed is decided by thread scheduler and thread priority is used by the thread scheduler to make that decision.

Java Thread Priority

When a Java thread is created, it inherits its priority from the thread that created it. Thread's priority can be modified at any time after its creation using the setPriority() method which is a member of Thread class.

General form

public final void setPriority(int newPriority)

Here newPriority specifies the new priority setting for the calling thread. The priority level ranges from 1 (least important) to 10 (most important) and the default priority level is 5 .

In Thread class, three constants are provided to define min, max and default priority for a thread.

     /**
     * The minimum priority that a thread can have.
     */
    public final static int MIN_PRIORITY = 1;

    /**
     * The default priority that is assigned to a thread.
     */
    public final static int NORM_PRIORITY = 5;

    /**
     * The maximum priority that a thread can have.
     */
    public final static int MAX_PRIORITY = 10;

Let's write some code to see priorities in action. First we'll write a program where no priorities are set so each thread will have the default priority.

Example code

//This class' shared object will be accessed by threads
class LoopValues implements Runnable{

    @Override
    public void run() {
        for (int i = 1; i <= 10; i++) {
            System.out.println(Thread.currentThread().getName() + " : " + i);
        }
        
    }
}

public class ThreadPriorityDemo {
    public static void main(String[] args) {
        Thread thread1 = new Thread(new LoopValues(), "Thread-1");
        Thread thread2 = new Thread(new LoopValues(), "Thread-2");            
        thread1.start();
        thread2.start();           
        try {
            
            //Wait for the threads to finish
            thread1.join();
            thread2.join();
            
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
            
        System.out.println("Done with looping values");
    }
}

Output

Thread-1 : 1
Thread-1 : 2
Thread-1 : 3
Thread-1 : 4
Thread-2 : 1
Thread-2 : 2
Thread-2 : 3
Thread-2 : 4
Thread-2 : 5
Thread-2 : 6
Thread-2 : 7
Thread-2 : 8
Thread-2 : 9
Thread-2 : 10
Thread-1 : 5
Thread-1 : 6
Thread-1 : 7
Thread-1 : 8
Thread-1 : 9
Thread-1 : 10
Done with looping values

Here it can be seen that output has a mix of both the threads. Please note that the output may vary with each run.

Example code with thread priority

Now we'll set the priorities so that one thread has the max priority(10) and another has the least priority(1).

//This class' shared object will be accessed by threads
class LoopValues implements Runnable{

    @Override
    public void run() {
        for (int i = 1; i <= 10; i++) {
            System.out.println(Thread.currentThread().getName() + " : " + i);
        }
        
    }
}

public class ThreadPriorityDemo {
    public static void main(String[] args) {
        Thread thread1 = new Thread(new LoopValues(), "Thread-1");
        Thread thread2 = new Thread(new LoopValues(), "Thread-2");      
        thread1.setPriority(Thread.MAX_PRIORITY);
        thread2.setPriority(Thread.MIN_PRIORITY);
        thread1.start();
        thread2.start();           
        try {
            
            //Wait for the threads to finish
            thread1.join();
            thread2.join();
            
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
            
        System.out.println("Done with looping values");
    }

}

Output

Thread-1 : 1
Thread-1 : 2
Thread-1 : 3
Thread-1 : 4
Thread-1 : 5
Thread-1 : 6
Thread-1 : 7
Thread-1 : 8
Thread-1 : 9
Thread-1 : 10
Thread-2 : 1
Thread-2 : 2
Thread-2 : 3
Thread-2 : 4
Thread-2 : 5
Thread-2 : 6
Thread-2 : 7
Thread-2 : 8
Thread-2 : 9
Thread-2 : 10
Done with looping values

It can be seen that the thread which has the highest priority finishes first then the second thread starts its execution. Please note that even with this priority setting there may be a mixed output or the thread with the min priority may execute first. That brings us to the next section why we can't rely that much on thread priority.

Caution with thread priorities

Thread priority rules are dependent on the host platform (native OS). Host platform may have different priorities for the threads which may be more than what priorities are defined in Java or may be less than that. Java run time system maps the thread priorities to the priority levels of the host platform. So JVM may schedule a thread according to the priority defined in Java multithreading but when that thread actually gets the CPU cycle also depends upon the priorities defined by the host platform.

That's all for this topic Thread priorities in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Java Multi-threading interview questions
  2. Volatile in Java
  3. Can we start the same thread twice in Java
  4. What if run() method called directly instead of start() method
  5. Thread states in Java multithreading
  6. Synchronization in Java multithreading

You may also like -

No comments:

Post a Comment