Change Thread Priority : Thread Priority « Thread « Java Tutorial






  1. A priority tells the operating system how much resource should be given to each thread.
  2. A high-priority thread is scheduled to receive more time on the CPU than a low-priority thread. A method called Thread.setPriority() sets the priority of a thread. Thread class constants can be used to set these.
class CounterThread extends Thread {
  String name;
  public CounterThread(String name) {
    super();
    this.name = name;
    
  }

  public void run() {
    int count = 0;
    while (true) {
      try {
        sleep(100);
      } catch (InterruptedException e) {
      }
      if (count == 50000)
        count = 0;
      System.out.println(name+":" + count++);
    }
  }

}

public class MainClass{
    public static void main(String[] args) {
      CounterThread thread1 = new CounterThread("thread1");
      thread1.setPriority(10);
      CounterThread thread2 = new CounterThread("thread2");
      thread2.setPriority(1);
      thread2.start();
      thread1.start();
    }
}








10.3.Thread Priority
10.3.1.Change Thread Priority
10.3.2.Demonstrate thread priorities.
10.3.3.Minimum and Maximum Priority Threads
10.3.4.This class demonstrates how to set Priority