Multithreading - ThreadPriority

Java provides us a way by which we can define priority for a thread.

The acceptable values for thread priority are from 1 to 10. 1 being minimum, 10 being maximum. By default, normal priority is 5 and thread scheduler works based on that.

Consider the following program :

MyThreadExtendingThreadClass myThreadExtendingThreadClass = new MyThreadExtendingThreadClass();myThreadExtendingThreadClass.setPriority(2);
MyThreadImplementingRunnableInterface myThreadImplementingRunnableInterface = new MyThreadImplementingRunnableInterface();Thread thread = new Thread(myThreadImplementingRunnableInterface);thread.setPriority(10);

thread.start();myThreadExtendingThreadClass.start();

If you execute this program , you will see that the threads now follow the assigned priority and the thread extended by Thread class executes after the thread implemented by Runnable completes.

Also, note that if you give priority other than acceptable values, it throws an IllegalStateArgumentException.

An example for showing thread priority can be found here

Comments

Popular posts from this blog

Collection Framework - HashSet And LinkedHashSet class

Collection Framework - Cursors in Java

Hashed data structures