How to stop execution of a thread in Java

Stop Execution of a Thread in Java

How to stop execution of a thread in Java

We can stop the thread execution by using these three methods

  • yield()
  • join()
  • sleep()

yields() method of thread class:


we call this yield() method by writing Thread.yield(). This method causes to pause current executing of a thread to give the chance to the waiting thread of same priority. If there is no waiting thread or all waiting thread have low priority than the same thread can continue its execution.

Stop Execution of a Thread in Java

consider currently, T4 thread is executing and if Thread.yield() is called then thread T4 execution get paused and it will give chance to other thread of same priority. T4 will go to a wait state and will give chance to T1 thread as Thread T4 and T1 have the same priority.

If the yield() method is called, the thread goes from Running state to Ready/Run state.

Question:

A thread which is yield, when it will get a chance to execute again?
Ans- It depends on CPU scheduler.

Sample code to understand the yield method concept

class MyThread extends Thread
{
 public void run()
 {
  for(int i=0; i<=3; i++)
  {
  System.out.println(“child thread”);
  Thread.yield();
  }
 }
}
class XadminYieldDemo
{
 public static void main(String args[])
 {
  MyThread t = new MyThread();
  t.start();
  for(int i=0; i<=3; i++)
  {
  System.out.println(“main thread”);
  }
 }
}

Explanation:
In the above code main thread get more chance then child thread to execute, because child thread calls yield method.

Join() method of thread class:

If a thread wants to wait until completing some other thread then we should go for the join() method.
Stop Execution of a Thread in JavaAccording to the above diagram, if thread t1 wants to wait until thread t2 completes its task. Then t1 has to call join method on t2 like t2.join(). If t1 execute t2.join() then immediately t1 will enter into a wait state until t2 completes its task. Once the t2 completes its task then t1 can continue its execution.

A prototype of join() method:

  • public final void join(); This throws an interrupted exception
  • public final void join(long ms); This throws an interrupted exception
  • public final void join(long ms, int ns); This throws an interrupted exception.

Case 1#
Sample code to understand the join method concept.

class MyThread extends thread
{
  public void run()
  {
  for(int i=0; i<=3; i++)
    {
    System.out.println(“child thread executing”);
    try
      {
      Thread.sleep(5000);
      }
    catch(Exception e)
      {
      }
    }
  }
}
class XadminJoinDemo
{
public static void main(String args[])
  {
  MyThread t = new MyThread();
  t.start();
  t.join();
  for(int i=0; i<=3; i++)
    {
    System.out.println(“Main thread is executing...”)
    }
  }
}

Explanation:
Firstly, child thread will execute completely then the main thread will execute as t.join() method.

Case 2#
Waiting of child thread until completing the main thread for this child thread should have main thread reference.

Sample code:

class MyThread extends Thread
{
  static Thread mt; // reference of main thread
  public void run()
  {
  try
    {
    mt.join(); // child thread wait() till the main thread complete.
    }
    catch(Exception e)
    {
    }
    for(int i=0; i<=3; i++)
    {
    System.out.println(“Child Thread”);
    }
  }

class XadminJoinDemo
{
  public static void main(Strings args[])
  {
  MyThread mt= Thread.currentThread();
  MyThread t = new Mythread();
  t.start();
  for(int i=0; i<=3; i++)
    {
    System.out.println(“Main Thread”);
    Thread.sleep(1000);
    }
  }
}

Output:

Main Thread
Main Thread
Main Thread
Child Thread
Child Thread
Child Thread

 

Case3#
If both thread i.e, main thread and child thread both call join(), then both thread will wait forever and a program will be stuck.
Sample code:

class MyThread extends Thread
{
  static Thread mt; // reference of main thread
  public void run()
  {
    try
    {
    mt.join(); // child thread wait() till the main thread complete.
    }
    catch(Exception e)
    {
    }
    for(int i=0; i<=3; i++)
    {
    System.out.println(“Child Thread”);
    }
  }

class XadminJoinDemo
{
  public static void main(Strings args[])
  {
  MyThread mt= Thread.currentThread();	
  MyThread t = new Mythread();
  try
    {
    t.join(); // Main thread will wait() till the child thread complete.
    }
    catch(Exception e)
    {
    }
    for(int i=0; i<=3; i++)
    {
    System.out.println(“Main Thread”)
    Thread.sleep(1000);
    }
  }
}

Sample code:

Class Xadmin
{
  public static void main(String args[])
  {
  Thread.currentThread().join(); // This will executed by main thread
  }
}

Explanation:
Here, Main thread wants to wait till the time of main thread complete its task. A deadlock situation will occur. If thread calls join method on the same thread itself then the program will be a struct(Dead Lock) here, a thread has to wait an infinite amount of time.

Sleep method of thread class:


If a thread doesn’t want to perform its work for any amount of time and thread wants to wait then sleep() method should be called on it.

Stop Execution of a Thread in Java

Complete signature of sleep() method:

  • public static native void sleep(long ms)
  • public static void sleep(long ms, int ns); throws Interrupted exception

Sample code for the sleep method:

class Xadmin
{
 public static void main(Static args[]) throws Interrupted exception
 {
 for(int i=0; i<=10; i++)
  {
  System.out.println(“value of i”+i);
  Thread.sleep(5000);
  }
 }
}

How a thread can be interrupted by another thread?


Thread class contain one method called interrupt() method. The signature of the interrupt method: public void interrupt();
Thread can interrupt a sleeping thread or wait for a thread by using the interrupt method of thread class.

Sample code for the thread class:

class XadminThread extends Thread
{
  public void run()
  {
  try
    {
    for(int i=0; i<=3; i++)
      {
      System.out.println(“I am a lazy thread”);
      Thread.sleep(2000);
      }
    }
catch(InterruptedException e)
  {
  System.out.println(“I got interrrupted”);
  }
  }
}
class ThreadInterrupted
{
  public static void main(String args[])
    {
    XadminThread t = new XadminThread();
    t.start();
    t.interrupted(); // main thread interrrupts to child thread
    System.out.println(“end of the main”);
    }
}

A loophole in the interrupt method:


If interrupt() method is invoked by any thread and if any thread is not waiting nor sleeping then interrupt method will not get wasted. It will wait for the thread to enter in sleep or in a wait state. If Interrupt() method is invoked and if the target thread never entered into sleep or a wait state in its lifetime then there is no impact of interrupt call method. This is the only case where the interrupt method call will be wasted.
Sample code:

class XadminThread extends Thread
  {
  public void run()
    {
    for(int i=0; i<=1000; i++)
      {
      System.out.println(“ I am lazy thread”+i);
      }
      System.out.println(“ I am entering in to sleeping state”+i);
      try
      {
      Thread.sleep(1000);
      }
      catch(InterruptedException e)
      {
      System.out.println(“I got interrupt”);
      }
    }
  }
class ThreadSleepDemo
  {
  public static void main(String args[]);
    {
    XadminThread t = new XadminThread();
    t.start();
    t.interrrupt();
    System.out.println(“End of the main method”);
    }
  }

Comparison of yield() , join(), and sleep() methods:

Property yield() join() sleep()
purpose If the thread wants to pause its execution and give chance to other same priority thread to execute then yield() is used If the thread wants to wait() until completing some other thread then we should go for join() If a thread doesn’t want to perform any operation for a particular amount of time then go for the sleep() method
It is overload No Yes Yes
Is it final No Yes No
Is it throws InterruptedException No Yes Yes
Is it a native method Yes No sleep(long ms) is native

sleep(long ms, int ms) is non-native

Is it a static method yes No Yes

Conclusion:


In this article, we have learned the ways to stop or prevent the execution of a thread. We also learned the three methods of the thread class with their differences. Thread class in Java programming is a very important topic for the interview point of purpose. Multithreading is one of the most asked topics by the interviewer in the interview.
Please, feel free to drop a comment in the below comment box, if you have any doubt regarding the topic or you want to share more information about the topic. Happy Learning!

READ NOW :- Ultimate Guide to Thread Life Cycle