This is very interesting question where interviewees thread basics basic will be tested. Interviewers tend to know user’s knowledge about main thread’s and thread invoked by main thread.
We will try to address the problem by creating new thread which will run infinitely until certain condition is satisfied and will be called by main Thread.
- Infinitely running thread can be stopped using boolean variable.
- Infinitely running thread can be stopped using interrupt() method. But stop() is a deprecated method.
Let’s understand Why stop() method is deprecated :
Stopping a thread with Thread.stop causes it to release all of the monitors that it has locked. If any of the objects previously protected by these monitors were in an inconsistent state, the damaged objects become visible to other threads, which might lead to unpredictable behavior.
1) Logic behind terminating or stopping infinitely running thread using boolean variable>
Logic behind the program is that main Thread will call newThread and newThread will keep on running continuously/infinitely, but mainThread will be running intermittently and be waiting for user to press enter. As soon as user will press enter main Thread will update boolean variable and which in turn will help us breaking continuously/infinitely running thread by breaking loop.
Program to terminate infinitely running thread using boolean variable>
class MyRunnable implements Runnable {
boolean continueThread=true;
public void run() {
int i = 0;
while (true)
if (continueThread) {
try {
System.out.println(i++);
Thread.sleep(1000);
System.out.println("Please press enter key to stop "
+Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
} else{
System.out.println(Thread.currentThread().getName()+" ENDED");
break;
}
}
}
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class TerminatingThread {
public static void main(String args[]) throws Exception {
MyRunnable obj = new MyRunnable();
Thread t = new Thread(obj,"Thread-1");
t.start();
System.out.println(Thread.currentThread().getName()
+" thread waiting for user to press enter");
System.in.read();
obj.continueThread = false;
System.out.println(Thread.currentThread().getName()+" thread ENDED");
}
}
/*OUTPUT
main thread waiting for user to press enter
0
Please press enter key to stop Thread-1
1
Please press enter key to stop Thread-1
2
Please press enter key to stop Thread-1
3
Please press enter key to stop Thread-1
4
main thread ENDED
Please press enter key to stop Thread-1
Thread-1 ENDED
*/
|
What happened in above program?
Main thread started Thread-1, execution control entered while loop and we checked boolean variable continueThread which was true and we kept on running Thread-1, but main thread was running intermittently and waiting for user to press enter (i.e. main thread was in waiting state). Now, the question comes how main thread entered from running to waiting state, well the answer is System.in.read() caused it, and as soon as user pressed enter, continueThread’s value was changed to true and Thread-1’s if condition was no more satisfied and we breaked while loop from else and Thread-1 went into dead state.
2) Logic behind terminating or stopping infinitely running thread using interrupt() method>
Before stopping thread by using interrupt() method i’ll like you to brief about the method -
interrupt() >
When thread is interrupted, if it in waiting state caused by invocation of wait(), sleep or join() method then its interrupt status will be cleared and it will receive an InterruptedException.
Thread can only only interrupt themselves, if any other thread tries to interrupt thread than it may cause SecurityException to be thrown.
Logic behind the program is that main Thread will call newThread and newThread will keep on running continuously/infinitely until not being interrupted, but mainThread will be running intermittently and be waiting for user to press enter. As soon as user will press enter main Thread will call interrupt() method on newThread and in run() method we will catch that exception to stop continuously/infinitely running newThread.
Program to terminate infinitely running thread using interrupt() method>
class MyRunnable implements Runnable {
public void run() {
int i = 0;
try {
while (!Thread.currentThread().isInterrupted()) {
Thread.sleep(1000);
System.out.println(i++ + " Please press enter key to stop "
+ Thread.currentThread().getName());
}
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " ENDED");
}
}
}
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class TerminatingThreadUsingInterrupt {
public static void main(String args[]) throws Exception {
MyRunnable obj = new MyRunnable();
Thread t = new Thread(obj, "Thread-1");
t.start();
System.out.println(Thread.currentThread().getName()
+ " thread waiting for user to press enter");
System.in.read();
t.interrupt();
System.out.println(Thread.currentThread().getName() + " thread ENDED");
}
}
/* OUTPUT
main thread waiting for user to press enter
0 Please press enter key to stop Thread-1
1 Please press enter key to stop Thread-1
2 Please press enter key to stop Thread-1
3 Please press enter key to stop Thread-1
main thread ENDED
Thread-1 ENDED
*/
|
RELATED LINKS>
Race Condition >
Race condition in multithreading and it's solution
DeadLock and it’s detection >
Deadlock in multithreading - program to form DeadLock, solving DeadLock, measures to avoid Deadlock.
VisualVM - Thread dumps - Generating and analyzing Thread Dumps using VisualVM - step by step detail to setup VisualVM with screenshots
JSTACK - Thread dumps - Generating and analyzing Thread Dumps using JSATCK - step by step detail to setup JSTACK with screenshots
Reason why suspend() and resume() methods are deprecated and Deadlock prone
destroy() method in java - usage, reason why destroy() method is deprecated and Deadlock prone.
Important Thread methods (salient features, usage with programs)>
Join() method - ensure all threads that started from main must end in order in which they started and also main should end in last. Types of join() method-10 salient features of join
Sleep() method in threads - 10 key features with programs
Yield() method in threads - 8 key features with programs
Wait() and notify() methods- Definition, 8 key features, solving consumer producer problem with & without these methods and consequences of not using wait() and notify() methods.
Daemon threads - 12 salient features of Daemon Thread
2 alternate ways to stop thread, as stop() method is deprecated
Using Suspend and resume method in threads
Differences between important thread methods >
Difference between wait() and sleep() method in threads
Differences and similarities between yield() and sleep() in threads
Difference between notify() and notifyAll() methods, with program
Difference between wait() and wait(long timeout) -What will be Thread states
Guidelines to threadsafe code >
Guidelines to thread safe code, most important point we must take care of in multithreading programs
Interviews >