The methods to prevent Thread execution(Yield/Join/Sleep)

Yield Method

  • Yield method causes to pause the current executing thread to give the chance for waiting threads of same priority.
  • If there is no waiting thread or all waiting threads have low priority then same thread can continue its execution.
  • If multiple threads are waiting with same priority then which waiting thread will get the chance we cannot expect it depends on the thread scheduler.
  • The thread which is yielded when it will get the chance once again it depends on thread scheduler and we can predict it exactly.
  • If your schedular/processor does not support preemptive scheduling then yield method may not work on that platform.
public static native void yield();
public class ThreadNameDemo {
	public static void main(String[] args) {
		Thread t = new Thread(new TempThread());
		t.start();
		for(int i=0; i<10;i++) {
			Thread.yield();
			System.out.println("Main Thread : "+i);
		}
	} 
}
class TempThread implements Runnable{
	@Override
	public void run() {
		for(int i=0; i<10;i++) {
			Thread.yield();
			System.out.println("Child Thread : "+i);
		}
	}
}

Join Method

Case 1 : Main Thread Call join method on Child Thread Object (Main Thread waits for child thread to complete)

  • If a thread wants to wait until completing some other thread then we should go for join method.
  • For example : If a thread T1 wants to wait until completing T2 then T1 has to call T2.join()
  • If T1 executes T2.join() then immediately T will be entered into waiting state until T2 thread is completed.
  • Once T2 thread completes then T1 thread can continue its execution.
  • We can also ask a thread to wait for a thread for some fixed time, by passing the time parameter in the join() method.
  • If a Thread call a join() method on itself then the program will be stuck for ever in deadlock.
public final void join()  throws InterruptedException
public final void join(long milliseonds)  throws InterruptedException
public final void join(long milliseonds, int nanoseconds)  throws InterruptedException
package com.demo3;

public class ThreadNameDemo {
	public static void main(String[] args) throws InterruptedException {
		Thread t = new Thread(new TempThread());
		t.start();
		t.join(1000);
		for(int i=0; i<10;i++) {
			System.out.println("Main Thread : "+i);
		}
	} 
}
class TempThread implements Runnable{
	@Override
	public void run() {
		for(int i=0; i<10;i++) {
			try {
				Thread.sleep(300);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("Child Thread : "+i);
		}
	}
}

Output :

Child Thread : 0
Child Thread : 1
Child Thread : 2
Main Thread : 0
Main Thread : 1
Main Thread : 2
Main Thread : 3
Main Thread : 4
Main Thread : 5
Main Thread : 6
Main Thread : 7
Main Thread : 8
Main Thread : 9
Child Thread : 3
Child Thread : 4
Child Thread : 5
Child Thread : 6
Child Thread : 7
Child Thread : 8
Child Thread : 9

Case 2 : Child Thread class join method on main method. (Child Thread waiting for main Thread to complete.)

public class ThreadNameDemo {
	public static void main(String[] args) throws InterruptedException {
		Thread t = new Thread(new TempThread(Thread.currentThread()));
		t.join();
		for(int i=0; i<5;i++) {
			System.out.println("Main Thread : "+i);
		}
	} 
}
class TempThread implements Runnable{
	public static Thread mainThread;
	TempThread(Thread t){
		mainThread = t;
	}
	@Override
	public void run() {
		try {
			mainThread.join();
			for(int i=0; i<5;i++) {
				Thread.sleep(300);
				System.out.println("Child Thread : "+i);
			}
		}catch(Exception e) {
			System.out.println("Exception has been caught : "+e);
		}
	}
}

Output :

Main Thread : 0
Main Thread : 1
Main Thread : 2
Main Thread : 3
Main Thread : 4
Child Thread : 0
Child Thread : 1
Child Thread : 2
Child Thread : 3
Child Thread : 4

Case 3: Main Thread and child thread both waiting for each other to complete (Deadlock)

public class ThreadNameDemo {
	public static void main(String[] args) throws InterruptedException {
		Thread t = new Thread(new TempThread(Thread.currentThread()));
		t.start();
		t.join();
		for(int i=0; i<5;i++) {
			System.out.println("Main Thread : "+i);
		}
	} 
}
class TempThread implements Runnable{
	public static Thread mainThread;
	TempThread(Thread t){
		mainThread = t;
	}
	@Override
	public void run() {
		try {
			mainThread.join();
			for(int i=0; i<5;i++) {
				System.out.println("Child Thread : "+i);
			}
		}catch(Exception e) {
			System.out.println("Exception has been caught : "+e);
		}
	}
}

or you see the below example as deadlock

public class ThreadNameDemo {
	
	public static void main(String[] args) throws InterruptedException {
		Thread.currentThread().join();
		System.out.println("Hello Thread");
	}
}

Sleep Method

  • If a thread don’t want to perform any operation for a particular amount of time then we should go for sleep method.
  • Every sleep method throws Interrupted Exception which is checked exception hence when ever we are using sleep method it is mandatory to handle Interrupted Exception.
public static native void sleep(long milliseconds) throws InterruptedException
public static void sleep(long milliseconds, int nanoseconds) throws InterruptedException

public class ThreadNameDemo {

public static void main(String[] args) throws InterruptedException {
    for(int i=0; i<5;i++) {
        Thread.sleep(500);
        System.out.println("Main Thread : "+i);
    }
}

How a Thread can Interrupt another Thread

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

  • A Thread can interrupt a sleeping thread or waiting thread by using interrupt method of thread class.
  • If thread is not in sleeping state or waiting state then there is no impact of interrupt calling.
public void interrupt();
public class ThreadNameDemo {
	
	public static void main(String[] args) throws InterruptedException {
		Thread t = new Thread(new TempThread());
		t.start();
		t.interrupt();
		System.out.println("Thread stopped");
	} 
}
class TempThread implements Runnable{
	@Override
	public void run() {
		try {
			for(int i=0; i<5;i++) {
				System.out.println("Child Thread : "+i);
				Thread.sleep(1);
			}
		}catch(InterruptedException e) {
			System.out.println("InterruptedException has been caught : "+e);
		}
	}
}

Leave a Comment