Results 1 to 3 of 3
Thread: Interrupts
- 01-02-2010, 06:49 PM #1
Interrupts
I was reading the tutorial on Concurrency and I'm stumbled on this:
and this:Java Code:for (int i = 0; i < importantInfo.length; i++) { //Pause for 4 seconds try { Thread.sleep(4000); } catch (InterruptedException e) { //We've been interrupted: no more messages. [b] return;[/b] } //Print a message System.out.println(importantInfo[i]); }
this is the link: Interrupts (The Java™ Tutorials > Essential Classes > Concurrency)Java Code:for (int i = 0; i < inputs.length; i++) { heavyCrunch(inputs[i]); if (Thread.interrupted()) { //We've been interrupted: no more crunching. return; } }
My question are:
1. What does return; do in both codes?
2. In code 2, why/how would a for loop be interrupted? Thread.interrupt() was never called.Last edited by Lil_Aziz1; 01-02-2010 at 06:56 PM.
- 01-02-2010, 08:05 PM #2
perhaps another thread would have a handle to this thread and would have called its thread.interrupt().
interrupting a thread is the preferred way now to have one thread try to tell a second thread to stop running. Having the test for interrupted within the for loop of the first code sample around the thread sleep catches the interrupted exception that would get generated here if this thread was sleeping.
but for the second code block, im not entirely sure, but I believe that Thread.interrupted() test works there on its own to check if the thread has been interrupted, such as by another thread calling its thread.interrupt(), and this would cause the loop to preemptively exist, instead of continuing to finish its for() loop iterations. The Thread.interrupted is a static method that implicitly looks at the interrupted flag on the current thread.
In both cases the return causes the run() method in the thread to exit, which then would cause the thread to die. In theory without having these test for interrupted. the thread would continue to run until it finished naturally, ignoring the 'stop running' command from when the some other thread called thread.interrupt().
.. but in this example, I would expect the first code block would also need a test for if (Thread.interrupted() ), because if it was not in the part of thread.sleep() at the time it was interrupted, would it miss the interrupt() signal, or would the next time the Thread.sleep() is invoked, would it throw an InterruptedException?
- 01-02-2010, 08:18 PM #3
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,383
- Blog Entries
- 7
- Rep Power
- 17


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks