X

Play AlgoQuiz

Rate Us :



Share with Friends :

Menu

Thread priority :

Every thread in Java has some priority but the range of thread priority is '1 to 10'.(1 is least & 10 is highest). Thread class defines the following constants to define some standard priorities :-

Thread.MIN_PRIORITY : 1
Thread.NORM_PRIORITY : 5
Thread.MAX_PRIORITY : 10
Thread.LOW_PRIORITY //invalid
Thread.HIGH_PRIORITY //invalid

Thread Scheduler will use these priorities while allocating CPU space. The thread which is having highest priority will get chance first. If two threads have same priority then we can't expect exact execution order, it depends on Thread Scheduler.

Default priority :

The default priority is only for the main() method which is 5 but for all the remaining threads, it will be inherited from the parent i.e. whatever the priority is obtained by parent will be inherited to the child. Thread class defines the following two methods to get and set priority of a thread :-

public final int getPriority();
public final void setPriority(int p); 
/*allowed values are 1 to 10 otherwise we will get 
runtime exception saying IllegalArgumentException.*/ 

Example :

class Algo implements Runnable { public void run() { System.out.println("run()"); } } class Example { public static void main(String[ ] args) throws Exception { Algo r = new Algo(); Thread t = new Thread(r); t.setPriority(1); //line 1 t.start(); //starting of a thread System.out.println("main()"); } } //save as : Example.java //compile as : javac Example.java //run as : java Example

Output :

main() run()

Note :

If we are commenting line 1 then both main and child threads have the same priority '5' and hence we can't expect exact execution order and exact output. But if we aren't commenting line 1 then main thread has the priority '5' and child thread has the priority '1' and hence main thread will be executed first and then child thread and exact outcome will come.


The methods to prevent thread execution :

We can prevent thread execution by using following methods :-

  • yield()




  • join()




  • sleep()




yield() :-

yield() method pauses the current executing thread for giving the chance to the waiting thread of same priority to execute. If there is no waiting thread or all waiting threads have low priority then the same thread will continue it's execution once again.


Signature of yield() method :


public static native void yield()

When will the yielded thread get again a chance for execution is decided by Thread Scheduler.

class Algo implements Runnable
{
 public void run()
 {
   for(int i = 0 ; i <= 10 ; i++)
   {  
     Thread.yield(); //Line 1
     System.out.println("Child Thread");
   } //Job of thread
 }
}
class Example
{
 public static void main(String[ ] args)
  {
     Algo r = new Algo();
     Thread t = new Thread(r);
	 t.start(); //starting of a thread
     for(int i = 0 ; i <= 10 ; i++)
     {
       System.out.println("Main Thread");
     } //executing main thread
  }
}

If we are commenting Line 1 then both the threads will be executed simultaneously and we can't expect exact execution order.

If we are not commenting Line 1 then the chance of completing main thread first is high because child thread always calls yield() method to pause its execution.


join() :-

If a thread wants to wait until completion of execution of some other thread then we should use join() method.

If thread t1 executes t2.join() then t1 thread will enter into waiting state until t2 completes it's execution and once t2 will complete it's execution then t1 will continue it's execution.


Signature of join() method :


public final void join() throws InterruptedException
public final void join(long ms) throws InterruptedException
public final void join(long ms , int ns) throws InterruptedException

join() method is overloaded and every join() method throws InterruptedException. Hence, whenever we are using join() method, it is compulsory to handle InterruptedException either by try-catch or by throws otherwise we will get compile time error.

class Algo implements Runnable
{
 public void run()
 {
   for(int i = 0 ; i <= 10 ; i++)
   {  
     System.out.println("Child Thread");
   } //Job of thread
 }
}
class Example
{
 public static void main(String[ ] args) throws InterruptedException
  {
     Algo r = new Algo();
     Thread t = new Thread(r);
	 t.start(); //starting of a thread 
     t.join(); //Line 1
     for(int i = 0 ; i <= 10 ; i++)
     {
       System.out.println("Main Thread");
     } //executing main thread
  }
}

If we are commenting Line 1 then both threads will be executed simultaneously and we can't expect exact execution order and hence we can't expect exact output.

If we are not committing Line 1 then main thread will wait until completion of child thread. Hence in this case the output is expected as :

  • 10 times Child Thread followed by 10 times Main Thread

sleep() :-

If a thread don't want to perform any operation for a particular amount of time (just pausing for a while) then we should use sleep() method.

public final void sleep(long ms) throws InterruptedException
public final void sleep(long ms , int ns) throws InterruptedException

Whenever we are using sleep() method it is compulsory to handle InterruptedException otherwise we will get compile time error.

Example :

class Example { public static void main(String[ ] args) throws InterruptedException { System.out.println("Algo"); Thread.sleep(2000); System.out.println("Valley"); } } //save as : Example.java //compile as : javac Example.java //run as : java Example

Output :

Algo Valley

Interruption of a thread :

A thread can interrupt another sleeping or waiting thread. For this Thread class defines interrupt() method.

public void interrupt()
class Algo implements Runnable
{
 public void run()
 { 
   try
   {
    for(int i = 0 ; i <= 10 ; i++)
    {
      System.out.println("Child Thread"); 
      Thread.sleep(2000);
    }
   }
   catch(InterruptedException e)
   {
     System.out.println("Child Thread got interrupted");
   } 
 }
}
class Example
{
 public static void main(String[ ] args)
  {
     Algo r = new Algo();
     Thread t = new Thread(r);
     t.start(); //starting of a thread 
     t.interrupt(); //Line 1    
     System.out.println("End of Main Thread");
  }
}

If we are commenting Line 1 then the main thread won't interrupt child thread hence, both threads will be executed until completion.

If we are not commenting Line 1 then main thread interrupt the child thread hence raise InterruptedException. In this case the output has following possibility :

Child Thread
Child Thread got interrupted
End of Main Thread


Child Thread End of Main Thread Child Thread got interrupted
End of Main Thread Child Thread Child Thread got interrupted
Note :

We may not see the impact of interrupt call immediately.

Whenever we are calling interrupt() method, if the target thread is not in sleeping or waiting state then there is no impact immediately. Interrupt call will wait until the target thread enters into sleeping or waiting state. Once target thread enters into sleeping or waiting state then the interrupt call will impact the target thread.



X

MiniDoll :

MiniDoll is an application to learn with fun. You can play it to solve some tricky questions related to Java Programming. Either enjoy playing it alone or discuss with your friends to solve it. It is a simple approach to learn by solving questions. This application has different topics of Java and each topic is divided into three phases. Start solving from initial topic to final topic and by the end of every topic you can boost your concept of that topic.