Priority allow the scheduler to take the decision when the thread should be allowed to run, and in which order. The higher priority threads get more CPU time then lower priority threads. A lower priority thread can be preempted by higher priority thread. The threads having equal priority get equal CPU time.
To set a thread’s priority, use the setPriority( ) method, which belongs to Thread class. Prototypes is as
final void setPriority(int priorityValue)
Here, priority Value give the new priority for the calling thread. The value of priorityValue must be within the range MIN_PRIORITY and MAX_PRIORITY. Values of these constants are I and 10, respectively. A thread default priority is NORM_PRIORITY, which is currently 5. These priorities constants are defined as final variables within Thread.
You can get current priority value of the thread by calling the getPriority( ) method of Thread, shown here.
final int getPriority( )
Example:
public class Main
{
public void setPrioritiesOnThreads()
{
Thread thread1 = new Thread(new TestThread(1));
Thread thread2 = new Thread(new TestThread(2));
thread1.start();
thread2.start();
try
{
thread1.join ();
thread2.join ();
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
System.out.println(“Done.”);
}
public static void main(String[] args)
{
new Main().setPrioritiesOnThreads();
}
class TestThread implements Runnable
{
int id;
public TestThread(int id)
{
this.id = id;
}
public void run()
{
for (int i = 1; i <= 10; i++)
{
System.out.println(“Thread” + id + “: ” + i);
}
}
}
}
Output:
The output is without priority assigning to the thread. Both thread are executing not in exact order, but executing concurrently.
If we assign the priority to the thread then the code is given below.
public class Main
{
public void setPrioritiesOnThreads()
{
Thread thread1 = new Thread(new TestThread(1));
Thread thread2 = new Thread(new TestThread(2));
thread1.setPriority(Thread.MAX_PRIORITY);
thread2.setPriority(Thread.MIN_PRIORITY);
thread1.start();
thread2.start();
try
{
thread1.join ();
thread2.join ();
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
System.out.println(“Done.”);
}
public static void main(String[] args)
{
new Main().setPrioritiesOnThreads();
}
class TestThread implements Runnable
{
int id;
public TestThread(int id)
{
this.id = id;
}
public void run()
{
for (int i = 1; i <= 10; i++)
{
System.out.println(“Thread” + id + “: ” + i);
}
}
}
}
Now the thread1 has the highest priority so it executes first: