Thread Priority Concept Simplified in Java

0
151
Spread the love
  • 24
  • 34
  • 28
  • 23
  •  
  •  
  •  
  • 12
  •  
  •  
    121
    Shares

Thread Priority Concept Simplified in Java:

In my earlier post here I have shown details about a thread and how to create a thread. In this post, we will see an important property of a thread called Priority. In java, each thread is assigned a priority which affects the execution of the thread. By default, threads will be created with normal priority and threads with having same priority are given equal time slot to execute. Mostly it is a first come first serve basis.
Whenever multiple threads are ready for execution, the java will choose the highest priority thread and will execute. For a lower priority thread to gain control, one of the following condition should happen to a high priority thread:

  1. It stops running at the end of the run().
  2. It is made to sleep using sleep()
  3. It is made to wait using wait().
If another thread of a higher priority comes along the currently running thread will be preempted by the incoming thread along, forcing the current thread to move to runnable state. Higher priority threads will always preempt any lower priority thread.
Also, read here controlling deadlock and synchronization.
Although java does not guarantee much about how threads are scheduled it does guarantee that a thread with a priority higher than that of another thread will be scheduled first to run than the lower priority thread.
The priority of a thread is set when the Thread object is created by passing an integer to the constructor.
if an explicit priority is not set or specified, the Thread inherits the parent’s priority.
Before setting the priority of a Thread object, the setPriority() method checks the maximum allowable priority for the ThreadGroup that contains the Thread. It is done by calling the getMaxPriority() method on the ThreadGroup.
If the call to setPriority() tries to set the priority to a value that is higher than the maximum allowable priority for the ThreadGroup, the priority is set to the maximum priority the same as the ThreadGroup.
It is possible for the current priority of a Thread to be greater than the maximum allowable priority of the ThreadGroup. In that case, an attempt to raise the priority of the Thread results in its priority being lowered to the maximum priority.

How to set priority to a thread:


ThreadName.setPriority(int priorityNumber);

int priorityNumber is a constant ranging from 0 to 10. Most user-level processes should be NORM_PRIORITY+/- 1
An example:


class A extends Thread{
    public void run(){
        System.out.println("Running Thread A");
        for(int i=0;i<10;i++){
          System.out.println("Running from Thread A "+i);   
        }
         System.out.println("Ending Thread A");
    }
}
class B extends Thread{
    public void run(){
        System.out.println("Running Thread B");
        for(int i=0;i<10;i++){
          System.out.println("Running from Thread B "+i);   
        }
         System.out.println("Ending Thread B");
    }
}
class C extends Thread{
    public void run(){
        System.out.println("Running Thread C");
        for(int i=0;i<10;i++){
          System.out.println("Running from Thread C "+i);   
        }
         System.out.println("Ending Thread C");
    }
}
public class ThreadPriorityTest{
    public  static void main(String args[])
    {
        A threadA=new A();
        B threadB=new B();
        C threadC=new C();
        threadC.setPriority(Thread.MAX_PRIORITY);
        threadB.setPriority(threadA.getPriority()+2);
        threadA.setPriority(Thread.MIN_PRIORITY);
        System.out.println("Start thraed A");
        threadA.start();
        System.out.println("Start thraed B");
        threadB.start();
        System.out.println("Start thraed C");
        threadC.start();
        System.out.println("Out of main thread");
    }
}

output of the code:
$javac ThreadPriorityTest.java
$java -Xmx128M -Xms16M ThreadPriorityTest
Start thraed A
Start thraed B
Running Thread A
Start thraed C
Running from Thread A 0
Running from Thread A 1
Running from Thread A 2
Running from Thread A 3
Running Thread B
Out of main thread
Running from Thread A 4
Running from Thread B 0
Running from Thread B 1
Running Thread C
Running from Thread A 5
Running from Thread C 0
Running from Thread B 2
Running from Thread B 3
Running from Thread B 4
Running from Thread B 5
Running from Thread B 6
Running from Thread B 7
Running from Thread B 8
Running from Thread B 9
Ending Thread B
Running from Thread C 1
Running from Thread C 2
Running from Thread C 3
Running from Thread C 4
Running from Thread C 5
Running from Thread C 6
Running from Thread C 7
Running from Thread C 8
Running from Thread C 9
Ending Thread C
Running from Thread A 6
Running from Thread A 7
Running from Thread A 8
Running from Thread A 9
Ending Thread A

Another Example:


class clock implements Runnable{
    int tick=0;
    Thread t;
    private boolean isRunning=true;
    public clock(int priority)
    {
        t=new Thread(this);
        t.setPriority(priority);
    }
    public void run()
    {
        while(isRunning){
            tick++;
        }
    }
    public void stop()
    {
        isRunning=false;
    }
    public void start()
    {
        t.start();
    }
    public void join(){}
}
public class MyClockTest{
public static void main(String []args){
    Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
    //main thread is given highest priority
    clock bigHand=new clock(Thread.NORM_PRIORITY+2);
    clock smallHand=new clock(Thread.NORM_PRIORITY-2);
    //two thread are initialized with different priorities
    bigHand.t.setName("BigHand");
    smallHand.t.setName("SmallHand");
    smallHand.start();
    bigHand.start();
    //all three threads are running
    try{
        Thread.sleep(1000);
        //block the main thread 1 second
    }
    catch(Exception e){}
    smallHand.stop();
    if(bigHand.t.isAlive())
    {
         System.out.println(bigHand.t.getName()+"is running");
    }
     if(smallHand.t.isAlive())
    {
         System.out.println(smallHand.t.getName()+"is running");
    }
    bigHand.stop();
    try{
        bigHand.join();
        smallHand.join();
    }
    catch(Exception e){}

    System.out.println(smallHand.t.getName()+"is running for "+smallHand.tick);
    System.out.println(bigHand.t.getName()+"is running for "+bigHand.tick);

     }    
}

output of the code:
$javac MyClockTest.java
$java -Xmx128M -Xms16M MyClockTest
BigHandis running
SmallHandis running
SmallHandis running for 411997559
BigHandis running for 412531380

Don't miss out!
Subscribe To Newsletter

Receive top technical news, lesson ideas, travel tips and more!

Invalid email address
Give it a try. You can unsubscribe at any time.

Spread the love
  • 24
  • 34
  • 28
  • 23
  •  
  •  
  •  
  • 12
  •  
  •  
    121
    Shares

LEAVE A REPLY

Please enter your comment!
Please enter your name here