Ben Zaidi wrote:
As t is interrupted, it means the run() method will exit immediately. But what does line 68 signifies in this code? I understood the usage of t.join(1000) at line
58 which means that, currently stop the main thread for and wait for 1 second for MessageLoop to complete. If it doesn't just interrupt the
thread t. But what does line 68 means? Because after throwing the InterruptedException thread t will terminate and main will complete its
execution. Any pointers will be helpful.
when you call t.interrupt, the interrupted flag will be set, but the thread will be interrupted only if something is watchig this flag. The
Thread.sleep(4000); construction in run() method does watch the interrupded flag, so the t thread will be interrupded as soon as it tryies to execute next Thread.sleep(4000);. Between t.interrupt() and Thread.sleep(4000); the main thread teoretically can do something, so if you want to prevent this, you do t.join() after you set t.interrupt() just to wait while the thread will be fully interrupted.
in this particular program you can get this output if comment out t.join():
and the usage of t.join garantees this output:
And then, if you remove all Thread.sleep() construction with its InterruptedException catch block and include the for loop in some while(true) loop, the t thread will never terminate, just because nothing will check if the interrupted flag is set for the thread.