Concurrency in Java: Interrupting and Joining Threads
- 4.7/5
- 5459
- Jul 20, 2024
Interrupting a Thread
If any thread is in "sleeping" or "waiting" state, calling the interrupt() method on the thread, breaks out the sleeping or waiting state throwing "InterruptedException".
The thread is interrupted !!!
If the thread is not in the "sleeping" or "waiting" state, calling the interrupt() method performs normal behaviour and doesn't interrupt the thread but sets the interrupt flag to true.
In this scenario, we need to check for "isInterrupted()" and take the action accordingly, as shown in the example below:
The thread is interrupted !!!
Joining Threads
When we invoke the join() method on a thread, the calling thread goes into a waiting state. It remains in a waiting state until the referenced thread terminates.
Without join()
main: 0 Thread-0: 0 main: 1 main: 2 Thread-0: 1 main: 3 Thread-0: 2 main: 4 Thread-0: 3 Thread-0: 4
With join()
Thread-0: 0 Thread-0: 1 Thread-0: 2 Thread-0: 3 Thread-0: 4 main: 0 main: 1 main: 2 main: 3 main: 4
There are three overloaded join functions.
1) join()
It will put the current thread on wait until the thread on which it is called is dead. If thread is interrupted then it will throw InterruptedException.
2) join(long millis)
It will put the current thread on wait until the thread on which it is called is dead or specified time (milliseconds) is passes.
3) join(long millis, int nanos)
It will put the current thread on wait until the thread on which it is called is dead or specified time (milliseconds + nanos) is passes.