Java - Thread - Problem in one of the Sun's tutorial
Posted
by Yatendra Goel
on Stack Overflow
See other posts from Stack Overflow
or by Yatendra Goel
Published on 2010-05-03T08:53:36Z
Indexed on
2010/05/03
8:58 UTC
Read the original article
Hit count: 179
I was reading this Sun's tutorial on Thread.
I found a block of code there which I think can be replaced by a code of fewer lines. I wonder why Sun's expert programmers followed that long way when the task can be accomplished with a code of fewer lines.
I am asking this question so as to know that if I am missing something that the tutorial wants to convey.
The block of code is as follows:
t.start();
threadMessage("Waiting for MessageLoop thread to finish");
//loop until MessageLoop thread exits
while (t.isAlive()) {
threadMessage("Still waiting...");
//Wait maximum of 1 second for MessageLoop thread to
//finish.
t.join(1000);
if (((System.currentTimeMillis() - startTime) > patience) &&
t.isAlive()) {
threadMessage("Tired of waiting!");
t.interrupt();
//Shouldn't be long now -- wait indefinitely
t.join();
}
}
threadMessage("Finally!");
I think that the above code can be replaced by the following:
t.start();
t.join(patience); // InterruptedException is thrown by the main method so no need to handle it
if(t.isAlive()) {
// t's thread couldn't finish in the patience time
threadMessage("Tired of waiting!");
t.interrupt();
t.join();
}
threadMessage("Finally!");
© Stack Overflow or respective owner