Understanding Thread Priority

Here is a little refresher on concept of threads in Java

http://kamalmeet.com/java/multithreading-runnable-vs-thread/
http://kamalmeet.com/java/handling-multithreading-with-synchronization/
http://kamalmeet.com/java/synchronization-object-vs-class-level/

There can be times where you might want to give priority to one thread over another. Java provides you a way to do that by setting priority of threads.

Thread.setPriority

An Example

package test;

public class thread {

public static void main(String s[])
{
RunnableTest r=new RunnableTest();
for(int i=0;i<5;i++) { Thread t=new Thread(r); t.setName("t:"+i); t.setPriority(Thread.NORM_PRIORITY+i); t.start(); } } } class RunnableTest implements Runnable{ int count=0; public synchronized void test() { try { count++; System.out.println(Thread.currentThread().getPriority()); Thread.sleep(1000); //This will just introduce some delay System.out.println(Thread.currentThread().getName()+" says Hello from Runnable:"+count); } catch (Exception e) { e.printStackTrace(); } } @Override public void run() { test(); } }

But there is a catch. Threads are handled at operating system level, so Java is depending on OS to make sure thread priority is taken care of. Here is a good explanation of thread priority in Java being handled in different OS - http://www.javamex.com/tutorials/threads/priority_what.shtml