Java Concurrency – yield(), sleep() and join() Methods
Last Updated :
16 Jan, 2022
In this article, we will learn what is yield(), join(), and sleep() methods in Java and what is the basic difference between these three. First, we will see the basic introduction of all these three methods, and then we compare these three.
We can prevent the execution of a thread by using one of the following methods of the Thread class. All three methods will be used to prevent the thread from execution.
1. yield() Method
Suppose there are three threads t1, t2, and t3. Thread t1 gets the processor and starts its execution and thread t2 and t3 are in Ready/Runnable state. The completion time for thread t1 is 5 hours and the completion time for t2 is 5 minutes. Since t1 will complete its execution after 5 hours, t2 has to wait for 5 hours to just finish 5 minutes job. In such scenarios where one thread is taking too much time to complete its execution, we need a way to prevent the execution of a thread in between if something important is pending. yield() helps us in doing so.
The yield() basically means that the thread is not doing anything particularly important and if any other threads or processes need to be run, they should run. Otherwise, the current thread will continue to run.

Use of yield method:
- Whenever a thread calls java.lang.Thread.yield method gives hint to the thread scheduler that it is ready to pause its execution. The thread scheduler is free to ignore this hint.
- If any thread executes the yield method, the thread scheduler checks if there is any thread with the same or high priority as this thread. If the processor finds any thread with higher or same priority then it will move the current thread to Ready/Runnable state and give the processor to another thread and if not – the current thread will keep executing.
- Once a thread has executed the yield method and there are many threads with the same priority is waiting for the processor, then we can’t specify which thread will get the execution chance first.
- The thread which executes the yield method will enter in the Runnable state from Running state.
- Once a thread pauses its execution, we can’t specify when it will get a chance again it depends on the thread scheduler.
- The underlying platform must provide support for preemptive scheduling if we are using the yield method.
2. sleep() Method
This method causes the currently executing thread to sleep for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.
Syntax:
// sleep for the specified number of milliseconds
public static void sleep(long millis) throws InterruptedException
//sleep for the specified number of milliseconds plus nano seconds
public static void sleep(long millis, int nanos)
throws InterruptedException
Java
import java.lang.*;
public class SleepDemo implements Runnable {
Thread t;
public void run()
{
for ( int i = 0 ; i < 4 ; i++) {
System.out.println(
Thread.currentThread().getName() + " "
+ i);
try {
Thread.sleep( 1000 );
}
catch (Exception e) {
System.out.println(e);
}
}
}
public static void main(String[] args) throws Exception
{
Thread t = new Thread( new SleepDemo());
t.start();
Thread t2 = new Thread( new SleepDemo());
t2.start();
}
}
|
Output
Thread-1 0
Thread-0 0
Thread-0 1
Thread-1 1
Thread-0 2
Thread-1 2
Thread-1 3
Thread-0 3
Note:
- Based on the requirement we can make a thread to be in a sleeping state for a specified period of time
- Sleep() causes the thread to definitely stop executing for a given amount of time; if no other thread or process needs to be run, the CPU will be idle (and probably enter a power-saving mode).
3. join() Method
The join() method of a Thread instance is used to join the start of a thread’s execution to the end of another thread’s execution such that a thread does not start running until another thread ends. If join() is called on a Thread instance, the currently running thread will block until the Thread instance has finished executing. The join() method waits at most this many milliseconds for this thread to die. A timeout of 0 means to wait forever
Syntax:
// waits for this thread to die.
public final void join() throws InterruptedException
// waits at most this much milliseconds for this thread to die
public final void join(long millis)
throws InterruptedException
// waits at most milliseconds plus nanoseconds for this thread to die.
The java.lang.Thread.join(long millis, int nanos)
Java
import java.lang.*;
public class JoinDemo implements Runnable {
public void run()
{
Thread t = Thread.currentThread();
System.out.println( "Current thread: "
+ t.getName());
System.out.println( "Is Alive? " + t.isAlive());
}
public static void main(String args[]) throws Exception
{
Thread t = new Thread( new JoinDemo());
t.start();
t.join( 1000 );
System.out.println( "\nJoining after 1000"
+ " milliseconds: \n" );
System.out.println( "Current thread: "
+ t.getName());
System.out.println( "Is alive? " + t.isAlive());
}
}
|
Output
Current thread: Thread-0
Is Alive? true
Joining after 1000 milliseconds:
Current thread: Thread-0
Is alive? false
Note:
- If any executing thread t1 calls join() on t2 i.e; t2.join() immediately t1 will enter into waiting state until t2 completes its execution.
- Giving a timeout within join(), will make the join() effect to be nullified after the specific timeout.
Comparison of yield(), join(), sleep() Methods
Property |
yield() |
join() |
sleep() |
Purpose |
If a thread wants to pass its execution to give chance to remaining threads of the same priority then we should go for yield() |
If a thread wants to wait until completing of some other thread then we should go for join() |
If a thread does not want to perform any operation for a particular amount of time, then it goes for sleep() |
Is it overloaded? |
NO |
YES |
YES |
Is it final? |
NO |
YES |
NO |
Is it throws? |
NO |
YES |
YES |
Is it native? |
YES |
NO |
sleep(long ms)->native & sleep (long ms, int ns)-> non native |
Is it static? |
YES |
NO |
YES |
Similar Reads
Multithreading in Java
Multithreading is a Java feature that allows the concurrent execution of two or more parts of a program for maximum utilization of the CPU. Each part of such a program is called a thread. So, threads are lightweight processes within a process. Different Ways to Create ThreadsThreads can be created b
3 min read
Lifecycle and States of a Thread in Java
A thread in Java can exist in any one of the following states at any given time. A thread lies only in one of the shown states at any instant: New StateRunnable StateBlocked StateWaiting StateTimed Waiting StateTerminated StateThe diagram below represents various states of a thread at any instant: L
5 min read
Main thread in Java
Java provides built-in support for multithreaded programming. A multi-threaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.When a Java program starts up, one thread begins running i
4 min read
Java Concurrency - yield(), sleep() and join() Methods
In this article, we will learn what is yield(), join(), and sleep() methods in Java and what is the basic difference between these three. First, we will see the basic introduction of all these three methods, and then we compare these three. We can prevent the execution of a thread by using one of th
5 min read
Inter-thread Communication in Java
Inter-thread communication in Java is a mechanism in which a thread is paused from running in its critical section, and another thread is allowed to enter (or lock) the same critical section to be executed. Note: Inter-thread communication is also known as Cooperation in Java. What is Polling, and W
6 min read
Java Thread Class
Thread is a line of execution within a program. Each program can have multiple associated threads. Each thread has a priority which is used by the thread scheduler to determine which thread must run first. Java provides a thread class that has various method calls to manage the behavior of threads b
5 min read
What does start() function do in multithreading in Java?
We have discussed that Java threads are typically created using one of the two methods : (1) Extending thread class. (2) Implementing RunnableIn both the approaches, we override the run() function, but we start a thread by calling the start() function. So why don't we directly call the overridden ru
2 min read
Java Thread Priority in Multithreading
Java being Object-Oriented works within a Multithreading environment in which the thread scheduler assigns the processor to a thread based on the priority of the thread. Whenever we create a thread in Java, it always has some priority assigned to it. Priority can either be given by JVM while creatin
5 min read
Joining Threads in Java
java.lang.Thread class provides the join() method which allows one thread to wait until another thread completes its execution. If t is a Thread object whose thread is currently executing, then t.join() will make sure that t is terminated before the next instruction is executed by the program. If th
3 min read
Java Naming a Thread and Fetching Name of Current Thread
A thread can be referred to as a lightweight process. Assigning descriptive names to threads enhances code readability and simplifies debugging. Now let us discuss the different ways to name a thread in Java. Methods to Set the Thread NameThere are two ways by which we can set the name either be it
4 min read