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.

Conclusion

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 😊

Comments

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 connectionscachingretrying failed requeststhreadingresponse parsingerror 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 https://timesofindia.indiatimes.com/rssfeedstopstories.cms using the Retrofit library.

To work with Retrofit, we need three classes -  Model class to map the JSON dataInterfaces which defines the possible HTTP operationsRetrofit.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 response is returned as a Call object…

Threads in Java - Masterclass (Part 0)

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 processor busy can be a tough task e…

Material design profile page in Android

Hey everyone, some days back I was working on one my personal Android project. In that project, I was supposed to create a simple profile page for a user. This profile page was supposed to show some basic details of a user.

The output of this UI will be like this -
I created the profile page using material design and in this post, I am going to discuss a step by step tutorial to create a simple yet elegant profile page. Without further ado, let's get started.
Creating a new project Click on File ➤ New Project ➤ Empty Activity and fill the necessary details. Change styles.xml fileNavigate to app\src\main\res\values\styles.xmlChange the style value from DarkActionBar to NoActionBar as below<resources><!-- Base application theme. --><stylename="AppTheme"parent="Theme.AppCompat.Light.NoActionBar"><!-- Customize your theme here. --><itemname="colorPrimary">@color/colorPrimary</item><itemname="colorPrimaryDark&qu…