Ways to Prevent Thread Execution.

We can prevent thread execution by using the following methods.

  1. yield()
  2. join()
  3. sleep()

Lets see how we can use above three method one by one to prevent thread execution.

yield():

Syntax: public static void yield()

  • yield method in java is used to prevent thread execution, this method pauses the currently executing thread to give the change to other waiting threads of the same priority.
  • If there is no waiting thread or all waiting threads have low priority then the current thread can continue its execution.
  • If multiple threads are waiting with the same priority then which waiting thread gets the chance depends on the Thread Scheduler.
  • Note that some platforms do not provide proper support for the yield method.
  • Example:
  • In the above example if we comment the Line 1 then both threads will execute simultaneously and we can not expect which thread will complete first.
  • But if we add Line 1 then the child thread will always call the yield method because which main thread will get the chance more number of times and the chance of completing the main thread first is high.
Java Code
class Test {
public static void main(String args[]) throws InterruptedException {

MyThread t = new MyThread();
t.start();
for (int i = 0; i < 5; i++) {
System.out.println(“Main Thread”);
}
}
}

class MyThread extends Thread {
public void run() {
System.out.println(“Child Thread”);
Thread.yield(); // —- Line 1
}
}
Output:
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Child Thread

join():

Syntax

  1. public final void join()
  2. public final void join(long milliSec, int nanoSec)
  3. public final void join(long milliSec)
  • If a thread wants to wait until the completion of some other thread then we can use the join method which helps to prevent thread execution for current thread.
  • As shown in the example below let’s consider threads t1(Main Thread) and t2 (Child Thread). If Thread t1 wants to wait until completing t2 then t1 has to call t2.join().
  • Hence if t1 executes t2.join() then immediately t1 will enter into the waiting state until t2 completes.
  • Once t2 is completed then t1 can continue its execution.
  • Example for join()
  • If we see from the output main thread (t1) will always wait until the child thread(t2) is completed.
Java Code
class Test {
public static void main(String args[]) throws InterruptedException {
MyThread t2 = new MyThread();
t2.start();
t2.join();
for (int i = 0; i < 5; i++) {
System.out.println(“Main thread as t1”);
}

}
}

class MyThread extends Thread {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(“Child thread as t2”);
}
}
}
Output:
Child thread as t2
Child thread as t2
Child thread as t2
Child thread as t2
Child thread as t2
Main thread as t1
Main thread as t1
Main thread as t1
Main thread as t1
Main thread as t1
  • As shown in the following main thread t1 will wait until the time is given and then starts the execution. In this case, child thread t2 will always start its execution first.
  • If can not predict which thread will be completed first, we can predict which thread will start first.
  • In the following example try to change the time at Line 1 and check how output will varies. We can also change the value for i from 1000 to any other lower or higher values and check the behaviour.
Java Code
class Test {
public static void main(String args[]) throws InterruptedException {
MyThread t2 = new MyThread();
t2.start();
t2.join(1, 1); // —- Line 1
for (int i = 0; i < 100; i++) {
System.out.println(“—-t1—-“);
}

}
}

class MyThread extends Thread {
public void run() {
System.out.println(“Child”);
for (int i = 0; i < 1000; i++) { // —- Line 2
System.out.println(“t2”);
}
}
}
  • In the previous example replace t2.join(1, 1) with t2.join(1) at Line 1 and check the behavior of output for different timings. Also, check with the different values of ‘i’ at Line 2.
  • In this join(long milliSec), the child thread will always start first but which thread will complete first is unpredicted. (Note that if we increase the time too high then the child will always complete first and we have purposely made the child thread have a longer loop to observe the behavior of different waiting timings of the main thread).

sleep():

Syntax:

  1. public static void sleep(long millis)throws InterruptedException
  2. public static void sleep(long millis, int nanos)throws InterruptedException
  • If thread do not want to perform any operation for a particular amount of time then we can use sleep method.
  • As shown in example below.
Java Code
import java.util.Date;

class Test {
public static void main(String args[]) throws InterruptedException {
MyThread t = new MyThread();
t.start();
System.out.println(“Main Thread”);

}
}

class MyThread extends Thread {
public void run() {
System.out.println(new Date());
System.out.println(“Child Thrad before sleep for 5 sec.”);
try {
Thread.currentThread().sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(new Date());
System.out.println(“Child after sleep time expires”);
}
}
Output:
Main Thread
Mon Jun 20 20:16:00 IST 2022
Child Thrad before sleep for 5 sec.
Mon Jun 20 20:16:05 IST 2022
Child after sleep time expires

How a Thread can interrupt another thread?

  • A thread can interrupt a sleeping thread or waiting thread by using interrupt() method of Thread class.

Syntax: public void interrupt()

  • Whenever we are calling interrupt method if the target thread is not in sleeping state or waiting state then there is no impact of the interrupt call immediately, interrupt method will be waited until target thread is in sleeping or waiting state.
  • If the target thread never entered into sleeping or waiting state in its lifetime then there is no impact of the intercept call, this is only case where interrupt call will be wasted.
  • As shown in the below example, if we add t.interrupt(); in main thread, then main thread interrupts the child thread. In this case child thread will not wait for 5 seconds, we will get an InterruptedException and further execution of child code will continue (if exception is handled in try catch)
Java Code
import java.util.Date;

class Test {
public static void main(String args[]) throws InterruptedException {
MyThread t = new MyThread();
t.start();
System.out.println(“Main Thread”);
t.interrupt();
}
}

class MyThread extends Thread {
public void run() {
System.out.println(new Date());
System.out.println(“Child Thrad before sleep for 5 sec.”);
try {
Thread.currentThread().sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(new Date());
System.out.println(“Child after sleep time expires”);
}
}
Output:
Main Thread
Mon Jun 20 20:45:31 IST 2022
Child Thrad before sleep for 5 sec.

java.lang.InterruptedException: sleep interrupted
at java.base/java.lang.Thread.sleep(Native Method)
at MyThread.run(Test.java:17)


Mon Jun 20 20:45:32 IST 2022
Child after sleep time expires

-A blog by Shwetali Khambe

Related Posts