Tutorial :Java - Thread - Problem in one of the Sun's tutorial



Question:

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!");  


Solution:1

t.join(1000)   

That code isn't actually supposed to be as smart as possible, but it's there for demonstrating usage I guess


Solution:2

The example is meant to convey the two threads, main and the one you started, running at the same time. The code doesn't actually do anything useful, but Suns example will show the "Still waiting..." interspersed with messages from the thread that's printing strings.

If you're looking at it in the form of what the cod actually does, yes they both do the same thing. Both examples 1) Start thread t 2) Will wait up to patience ms 3) Interrupt thread t 4) Wait for it to die 5) Print "Finally" from the main thread


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »