-2

How does one set different priorities for different threads on JAVA? Let us assume I have three threads A,B,C..and i want A to be of high priority.. How do I set the priority value in each case? Can I get a sample code for that?

2 Answers2

1

Each thread have a priority. Priorities are represented by a number between 1 and 10. In most cases, thread scheduler schedules the threads according to their priority (known as preemptive scheduling).

There are 3 constant priorities defined in Thread class:

  • public static int MIN_PRIORITY
  • public static int NORM_PRIORITY
  • public static int MAX_PRIORITY

You can use it as follows:

public static void main(String args[]){  
  Test t1 = new Test();  
  Test t2 = new Test();  
  t1.setPriority(Thread.MIN_PRIORITY);  
  t2.setPriority(Thread.MAX_PRIORITY);  
  t1.start();  
  t2.start();  
 }  

But it is not guaranteed because it depends on JVM specification that which scheduling it chooses.

Read more here.

DimaSan
  • 12,264
  • 11
  • 65
  • 75
0

You can just call Thread.setPriority(int) on your thread objects.

The value has to be between Thread.MIN_PRIORITY and Thread.MAX_PRIORITY

benjamin.d
  • 2,801
  • 3
  • 23
  • 35