Thread Priority

In Java, thread priority is an integer value between MIN_PRIORITY (1) and MAX_PRIORITY (10) that determines the order in which threads are executed by the Java Virtual Machine (JVM). Higher priority threads are executed


  class Clicker implements Runnable
  {  
      int click = 0; 
      Thread t;

      private volatile boolean running = true;

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

      public void run()
      {
          while (running)
          { 
              click++;
          }
      }

      public void stop()
      {
          running = false;
      }

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

  class Thread2
  { 
      public static void main(String ar[])
      {    
          Thread.currentThread().setPriority(Thread.MAX_PRIORITY);

          Clicker hi = new Clicker(Thread.NORM_PRIORITY + 2);
          Clicker lo = new Clicker(Thread.NORM_PRIORITY - 2);

          lo.start();
          hi.start();

          try
          {
              Thread.sleep(600);
          }
          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);
      }
  }

Output: