Pin It

How to set a thread's priority in Java ?.


Program to demonstrate how to set a thread's priority in Java


package com.hubberspot.multithreading;

public class ProducerConsumerTest {


 public static void main(String[] args) {
  // 3. Create a thread by instantiating
  // an object from the class
  Thread producer = new Producer();
  Thread consumer = new Consumer();

  // 4.(i) Give Producer class thread a priority of 1 
  // i.e. it has minimum priority
  producer.setPriority(Thread.MIN_PRIORITY);

  // 4.(ii) Give Consumer class thread a priority of 10 
  // i.e. it has maximum priority
  consumer.setPriority(Thread.MAX_PRIORITY);

  // 5. Call the start() method of the 
  // thread object
  producer.start();
  consumer.start();
  // Overall three threads are created 
  // 1. for main method , 2. for the Producer class
  // 3. for the Consumer class  

 }

}

// 1. Create a class that extends Thread
class Producer extends Thread {
 // 2. Overload the run method to perform 
 // the desired task
 public void run(){

  for (int i = 0; i < 10; i++){

   System.out.println("I am Producer : Produced Apple " + i);
   // 1. one way to put thread to sleep
   // static method that pause current thread so that other thread
   // gets the time to execute
   //Thread.yield();   

  }
 }

}

class Consumer extends Thread {
 public void run(){

  for (int i = 0; i < 10; i++){

   System.out.println("I am Consumer : Consumed Apple " + i);
   //Thread.yield();

  }

 }
}



Output of the program : 


 
Please Give Us Your 1 Minute In Sharing This Post!
SOCIALIZE IT →
FOLLOW US →
SHARE IT →
Related Posts Plugin for WordPress, Blogger...

Post your related queries below ...

comments powered by Disqus
Powered by Blogger.
 
© 2012 Learn Java by Examples Template by Hubber Spot