posted by Marlene:
quote:
--------------------------------------------------------------------------------
what about wait or sleep for certain amount of time?
--------------------------------------------------------------------------------
If a thread invokes wait(int), sleep(int) or join(int), we expect the thread to block (stop executing). However, if the interruption status is true prior to any one of these 3 methods being called, the thread appears to return immediately. I don't think the thread stops executing.
code:
--------------------------------------------------------------------------------
class Test extends Thread { public void run() { interrupt(); //interrupt myself synchronized(this) { try { System.out.println("isInterrupted = " + isInterrupted()); System.out.println("wait " + System.currentTimeMillis()); wait(5000); } catch (InterruptedException e) { System.out.println("catch " + System.currentTimeMillis()); } } } public static void main(String[] args) { new Test().start(); }}isInterrupted = truewait 1061329071606catch 1061329071606
Hi Marlene:
I believe the same thread is running again because:
1. There is only one thread.
2. the interrupt status is set to true before even thread starts.
I think this is what is happening:
a. interrupt is set to true
b. thread goes in wait state, continously checks for interrupt status
c. as interrupt is true, does not wait anymore
d. goes in ready to run state
e. as there is no other competing thread, this thread goes in running state right away.
All this is happening within the millisecond. so you see no time difference.
If you were to create two threads, you will see that two threads are inter-mingled, however there could / could not be any recorded time lapse in a particular run.
This is what is happening:
a. first thread goes in run state
b. it's interrupt is set to true
c. it goes in wait state
d. as it is already interrupted, it will go in ready to run state
e. but second thread will surely get time on cpu
and print at least one statement
f. first is caught
e. second goes in wait
g. second is caught
So I think that execution of wait() will stop the thread momentarily (because it has already been interrupted).
So I guess original question about "definitely stoping a thread" can be summerized:
"A thread can be definitely stopped for n milliseconds by invoking wait(n) or sleep(n) as long as it's interrupt is not set to true. However, if interrupt is set to true prior to invoking wait(n) or sleep(n), the thread will stop momentarily and run again"