Guys, I came across many apis suggesting that interrupt() is d best way to terminating a thread execution especially those performing blocking operations. i pretty much agree with it n also helpful for doing any clean-up act before ending thread execution. but what i e wanna ensure from all you guys is: how actually that thread wil end? is it by returning from the run()? becoz stop() n destroy() are to b ultimately avoided...
When you interrupt a thread -- it doesn't just end. It gets the interrupt signal, and your thread must deal with it. It is your thread's responsibility to clean up after itself.... Meaning....
1. If the thread gets interrupted while running, it will get marked as interrupted. It is the threads responsibility to check the flag, once in a while (if it is compute intensive), and abort the calculation and clean up after itself.
2. If the thread gets interrupted while in a wait(), sleep(), join(), etc., it will get an interrupted exception. Again, it is the threads responsibility to abort whatever it is doing and clean up after itself.
3. If the thread gets interrupted while doing IO, it is platform independant. On some systems, you will get an interrupted IO exception. On other systems, it won't work by itself. You also need to close the network or file that the thread is using. In this case, the thread will get an IO exception and can then check the interrupted flag.... And again, it is the threads responsibility to abort whatever it is doing and clean up after itself.
2nd: i believe I/O in java is synchronous or blocking...if there is just a single thread n it does read() in System.in then it wil definitely block.if i wanna implement it asynchronousely then I can do this reading in another thread while doing some work in current thread?
Is this approach right?
lemme know
Yes, threading is one solution to have your program not wait for a blocking IO operation. Another option is to using non-blocking IO via the NIO package.
Henry