The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Thread interrupt confusion Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Thread interrupt confusion" Watch "Thread interrupt confusion" New topic

Thread interrupt confusion

Lidija Sketa

Joined: Nov 12, 2008
Posts: 26
This is from Devaka's ExamLab practice 3 mock exam (thank you Devaka for this great simulator!).

I modified the code a little bit and added printouts but I still don't get it - why doesn't call to a.interrupt() cause InterruptedException?

The output is:
Thread main started sleeping
Thread Thread-1 started sleeping
Thread main stopped sleeping
Calling interrupt
After call to interrupt
Thread Thread-1 stopped sleeping

And another thing:

How can we be sure that the first thing after call to t.start() will be doDelay(100)? Why isn't the first thing that is being executed the code in thread's run method?
Ankit Garg

Joined: Aug 03, 2008
Posts: 9465

The call to interrupt doesn't causes interrupted exception as you are interrupting a instead of t (the actual thread). In the output, you can see there is one exception (Ex-B). That is because you call wait on an object whose lock the thread doesn't have...

SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Lidija Sketa

Joined: Nov 12, 2008
Posts: 26
Ooh, it's calling interrupt on a! I completely overlooked that fact, although for a second it looked suspicious

Thanks for clearing the confusion.

About the next statement that happens right after the thread.start() call: can we be sure that run() method will not execute right AFTER this call but rather will the next statement in the method?
In other words: in the previous example how can we be sure that doDelay(100); will execute before t.doDelay(1000)?
I agree. Here's the link:
subject: Thread interrupt confusion
It's not a secret anymore!