Java-Thread is a problem in one of the Sun tutorials
I was reading this Sun tutorial on the topic .
I found a block of code that I think could be replaced with less lines of code. I wonder why Sun expert programmers have followed this long path when a task can be accomplished with code with fewer lines.
I am asking this question to know what if I am missing something that the tutorial wants to convey.
The code block looks like this:
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 the above code can be replaced with the following:
t.start();
t.join(patience); // InterruptedException is thrown by the main method so no need to handle it
if(t.isAlive()) {
// t thread couldn't finish in the patience time
threadMessage("Tired of waiting!");
t.interrupt();
t.join();
}
threadMessage("Finally!");
a source to share
This example is for transferring two streams, the main one and the one you started working with at the same time. The code isn't really helpful, but the Suns example will show "Still waiting ..." interspersed with messages from the stream that prints lines.
If you look at it in terms of what cod actually does, yes, they both do the same. Both examples 1) Start thread t 2) Wait until patience
ms 3) Break thread t 4) Wait until it dies 5) Print "Finally" from the main thread
a source to share