Question 4:
Observe the following code:
public static void main(String [] args) {
Thread thread = new Thread(new WaitingForUserInput());
thread.setName("InputWaitingThread");
thread.start();
}
private static class WaitingForUserInput implements Runnable {
@Override
public void run() {
try {
while (true) {
char input = (char) System.in.read();
if(input == 'q') {
return;
}
}
} catch (IOException e) {
System.out.println("An exception was caught " + e);
};
}
}
Please choose the correct statement:
1. <p>We simply need to add <code>thread.interrupt();</code> in the end of the <code>main</code> method, which will stop the <code>"InputWaitingThread"</code> thread.</p>
2. <p>We simply need to add <code>thread.interrupt();</code> in the end of the <code>main</code> method, which will stop the <code>"InputWaitingThread"</code> thread.</p>
<p>And also add a new <code>catch</code> block in the <code>run</code> method inside the <code>WaitingForUserInput</code>, to handle an <code>InterruptedException</code>, and exit from the thread in that block of code.
3.
<p>The only ways to stop the application are:</p>
<p>1. For the user to type in the letter 'q'.</p>
2. Set <code>thread.setDaemon(true);</code></p> in the main method, before starting the thread
We simply need to add <code>thread.interrupt();</code> in the end of the<code>main</code> method, which will stop the <code>"InputWaitingThread"</code> thread.
<p>3. Forcefully kill the application</p>
4. <p>The application will stop immediately, since there is no <code>Thread.sleep()</code> call in the main method. And as soon as the <code>main</code> method exits, the application terminates. </p>
Question 2:
public static void main(String [] args) {
Thread thread = new Thread(new SleepingThread());
thread.start();
thread.interrupt();
}
private static class SleepingThread implements Runnable {
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000000);
} catch (InterruptedException e) {
}
}
}
}
Please choose the correct statement
1. <p>The application will stop anyway, when the main thread runs out of instructions to execute.</p>
2. <p>The application will terminate as soon as the <code>thread.interrupt();</code> code is executed.</p>
3. <p>Without modifying the code, the application will not stop.<br>We need to add a <code>return;</code> statement inside the <code>catch (InterruptedException e)</code> block to stop the application.</p>
4.
Answer
Q1 - 3
Q2 - 3
Q2
That's correct, the only way to programmatically stop the application is to make the thread a daemon. Unfortunately System.in.read() does not respond to Thread.interrupt();
Q2
That is correct. As a rule of thumb, never leave a catch block empty, and use the InterruptedException catch block to gracefully stop the current thread (by adding some print or cleaning code before returning from the run method)
No comments:
Post a Comment