Friday, 26 August 2016

Thread Priorities

Thread Priorities

Threads always run with some priority, that helps operating system to decide the order in which the threads are scheduled.
Java thread priorities lies between MIN_PRIORITY as a number 1 and MAX_PRIORITY as a number 10 and by default every thread has a priority of 5.
The scheduler uses preemptive, priority based scheduling mainly or time slicing scheduling to schedule the tasks
Preemptive, priority based Scheduling :- If a high priority thread enters into the runnable state than the high priority thread task executes until it  enters to wait/dead state or it will be bumped back to runnable if a higher priority task will came into existence.
Time Slicing Scheduling: - In this cases each thread is allocated a predefined slice of time and then it will sent back to runnable to give another thread a chance
Please note : Even if all threads are of equal priorities ,behavior is not guaranteed ,it means
1)      Scheduler can pick a thread to execute and run it until it enters to wait or dead state
2)      It can do time slicing to provide equal opportunities.

How to set a thread priority ?
Thread_object.setPriority(<int_value>);
Example:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package multithreadingtc;

/**
 *
 * @author shashank
 */

class Multithreading implements Runnable
{
     public void run()
    {
        for(int i=1;i<=10;i++)
        {
            System.out.println("run by" + Thread.currentThread().getName() + " remainder is i is " +i%10);
//            try
//            {
//                Thread.sleep(1000);
//            }catch(InterruptedException ex){}
        }
    }
}
public class MultithreadingTC{

    public static void main(String[] args) {
        // TODO code application logic here
        Multithreading th = new Multithreading();
        Thread t = new Thread(th);
        t.setName(" first");
        t.setPriority(8);
        t.start();
        Thread t2 = new Thread(th);
        t2.setPriority(6);
        t2.setName(" third");
        t2.start();
        Thread t1 = new Thread(th);
        t1.setName(" second");
        t1.setPriority(4);
        t1.start();
      
    }
   

}

No comments:

Post a Comment