Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

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 : 


 
 
© 2021 Learn Java by Examples Template by Hubberspot