Thread Priorities

Thread priorities are used by the thread scheduler to decide when each thread should be allowed to run. To set a thread's priority, use the setPriority( ) method, which is a member of Thread. This is its general form:


final void setPriority(int level)

The value of level must be within the range MIN_PRIORITY and MAX_PRIORITY. To return a thread to default priority, specify NORM_PRIORITY.

These priorities are defined as static final variables within Thread.

You can obtain the current priority setting by calling the getPriority( ) method of Thread, shown here:


final int getPriority( )

The following example demonstrates two threads at different priorities.

One thread is set two levels above the normal priority, as defined by Thread.NORM_PRIORITY, and the other is set to two levels below it.

The threads are started and allowed to run for ten seconds. Each thread executes a loop, counting the number of iterations. After ten seconds, the main thread stops both threads. The number of times that each thread made it through the loop is then displayed.


class MyThread implements Runnable {
  long click = 0;
  Thread t;
  private boolean running = true;

  public MyThread(int p) {
    t = new Thread(this);
    t.setPriority(p);
  }

  public void run() {
    while (running) {
      click++;
      try {
        Thread.sleep(50);
      } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }

  public void stop() {
    running = false;
  }

  public void start() {
    t.start();
  }
}

public class Main {
  public static void main(String args[]) {
    Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
    MyThread hi = new MyThread(Thread.NORM_PRIORITY + 4);
    MyThread lo = new MyThread(Thread.NORM_PRIORITY - 4);
    lo.start();
    hi.start();
    try {
      Thread.sleep(10000);
    } catch (InterruptedException e) {
      System.out.println("Main thread interrupted.");
    }
    lo.stop();
    hi.stop();
    try {
      hi.t.join();
      lo.t.join();
    } catch (InterruptedException e) {
      System.out.println("InterruptedException caught");
    }
    System.out.println("Low-priority thread: " + lo.click);
    System.out.println("High-priority thread: " + hi.click);
  }
}
Home 
  Java Book 
    Thread Conncurrent  

Thread:
  1. Multithreaded Programming
  2. The Main Thread
  3. Thread Name
  4. Thread sleep
  5. Thread Creation
  6. isAlive( ) and join( )
  7. Thread Priorities
  8. Thread Synchronization
  9. Interthread Communication
  10. Suspending, Resuming, and Stopping Threads
  11. Handle Uncaught Exception
  12. ThreadLocal variables