I tried to experiment with threads
. The question is:
What is the difference between
while nested in try/catch
andtry/catch nested in while
.
Here is the test:
myThread.start("first");
Thread.sleep(150);
myThread.interrupt();
myThread.start("second");
Thread.sleep(250);
myThread.interrupt();
myThread.start("third");
Thread.sleep(50);
myThread.interrupt();
myThread.start("forth");
myThread.interrupt();
myThread.start("fifth");
Thread.sleep(1);
myThread.interrupt();
I used two realisations of Thread class' run
method to test console output.
first realization:
public void run() {
while(!thread.isInterrupted()) {
try {
Thread.sleep(0);
System.out.println(thread.getName());
Thread.sleep(90);
} catch (InterruptedException e) {
}
}
}
first output
first
first
second
second
second
second
second
second
third
third
third
forth
fifth
fifth
fifth
fifth
fifth
fifth
fifth
fifth
fifth
.....`billion of 'fifth'`
fifth
This wasn't the output I wanted, so I changed my code a little and here is second realization:
public void run() {
try {
while(!thread.isInterrupted()) {
Thread.sleep(0);
System.out.println(thread.getName());
Thread.sleep(90);
}
} catch (InterruptedException e) {
}
}
second output:
first
first
second
second
second
third
fifth
And it's correct! I just swapped while
and try
. The output should be the same! Why so different?