Skip to main content

Threads in Java - yield(), sleep() and join() (Part 4)

Let's say we want to stop the execution of a thread. How do we do this? There are three methods in the Thread class which can be used to stop the execution of a thread. Let us discuss these methods one by one

1. Yield method

Suppose there are two threads A and B. A takes 10 minutes to complete a job while B takes only 10 seconds. At first, A and B both are in the RUNNABLE state then Thread Scheduler gives resources to A to run. Now B has to wait for 10 minutes to do a 10 seconds job. This very inefficient.

Wouldn't it be great if we have some way to prevent the execution of A in between so that B can run?
Fortunately, yield() method helps us in achieving this. 
  • If a thread calls yield() method, it suggests the Thread Scheduler that it is ready to pause its execution. But it depends upon the Thread Scheduler to consider this suggestion. It can entirely ignore it.
  • If a thread calls yield() method, the Thread Scheduler checks if there is any thread with same/higher priority is present. If it finds one such thread, then the Thread Scheduler moves the current thread to the RUNNABLE state and gives necessary resources to the thread with the same/higher priority and if not -  current thread will continue executing.
Code implementation for the same is below - 
Here the main thread is yielding for the child thread and once the child thread completes its execution, the control is returned to the main thread.
The output will be as follows
Thread-0 is running
Thread-0 is running
Thread-0 is running
Thread-0 is running
main is running
main is running
main is running
main is running

Important points

  1. If a yield method is called and there are more than one thread with the same priority, then we cannot specify which thread will execute.
  2. Upon executing yield() method, the thread goes to the RUNNABLE state from the RUNNING state.
  3. Once a thread is paused, we cannot deterministically say when will it next execute.

2. Sleep method

This method causes the thread to stop its execution for a specified amount of time (milliseconds). 
Thread.sleep() interacts with the thread scheduler to put the current thread in the wait state for a specified period of time. Once the wait time is over, thread state is changed to RUNNABLE and wait for the CPU for further execution. So the actual time that current thread sleep depends on the thread scheduler that is part of operating system.
Following code may be helpful in understanding the sleep() method -
Here we are stopping the execution of the thread for 2 seconds and when we print the output it will be returned as 2.002 seconds.

Important points

  1. It always pauses the current thread execution (guaranteed).
  2. The actual time thread sleeps before waking up and starts execution depends on system timers and schedulers. For a quiet system, the actual time for sleep is near to the specified sleep time but for a busy system, it will be a little bit more.
  3. When a thread calls this method, the monitor or lock acquired by this thread is not released.

3. Join method

The join() method is a mechanism of inter-thread communication. The join() method of a Thread instance is used to join the start of a thread’s execution to end of other thread’s execution such that a thread does not start running until another thread ends.
The join() method waits at most this much milliseconds for this thread to die. A timeout of 0 means to wait forever.
Following code may be helpful in understanding the join() method - 
The output for this program will be -
Current thread is: Thread-0
Is alive? true
Joining after 2 seconds
Current thread: Thread-0
Is alive? false

Giving a timeout within join() will make the join() effect to be nullified after the specific timeout.


In this post, we discussed methods to stop the execution of a thread. The code can be found in the commit on my GitHub.

Feel free to befriend me on FacebookTwitter or Linked In or say Hi by email.

Happy Coding 😊 and Happy Learning 😊


Popular posts from this blog

Parsing XML using Retrofit

Developing our own type-safe HTTP library to interface with a REST API can be a real pain as we have to handle many aspects - making connections caching retrying failed requests threading response parsing error handling, and more.  Retrofit, on the other hand, is a well-planned, documented and tested library that will save you a lot of precious time and headaches. In this tutorial, we are going to discuss how we can parse the XML response returned from  using the Retrofit library. To work with Retrofit, we need three classes -  Model class to map the JSON data Interfaces which defines the possible HTTP operations Retrofit.Builder class - Instance which uses the interface and the Builder API which allows defining the URL endpoint for the HTTP operation. Every method of the above interface represents on possible API call. The request type is specified by using appropriate annotations (GET, POST). The respon

Threads in Java - CountDownLatch (Part 12)

A CountDownLatch is a synchronizer which allows one thread to wait for one or more threads before starts processing. A good application of  CountDownLatch is in Java server-side applications where a thread cannot start execution before all the required services are started. Working A  CountDownLatch is initialized with a given count which is the number of threads it should wait for. This count is decremented by calling countDown() method by the threads once they are finished execution. As soon as the count reaches to zero, the waiting task starts running. Code Example Let us say we require three services, LoginService, DatabaseService and CloudService to be started and ready before the application can start handling requests. Output Cloud Service is up! Login Service is up! Database Service is up! All services are up. Now the waiting thread can start execution. Here, we can see that the main thread is waiting for all the three services to start before starting its own

Threads in Java - Masterclass (Part 0)

Threads in Java Multithreading is a way to introduce concurrency in a program. In any case, if there are parallel paths in our program (parts which do not depend on the result from another part), we can make use of multithreading. One should exploit this feature, especially with all these multiple core machines nowadays. Below are a few reasons why we should use multithreading - 1. Keep a process responsive There was once a time when you would print a document in MS Word and the application would freeze for an annoyingly long amount of time until the job finished. Eventually, Microsoft solved this problem by running a printing job parallel to the main thread/ GUI thread.  To be clear though, not only GUI apps but Network services have to keep an ear to the ground for new clients, dropped connections and cancellation requests. In either case, it is critical to do the heavy lifting on a secondary thread to keep the user satisfied. 2. Keep a processor busy Keeping a proc