wood burning stoves*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes interrupt method of Thread 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 "interrupt method of Thread" Watch "interrupt method of Thread" New topic
Author

interrupt method of Thread

laoniu gougou
Greenhorn

Joined: Jan 25, 2001
Posts: 25
Hi:
Anybody can tell me something about the interrupt method of a thread?
1) where is this method defined, Object or Thread?
2) What this method will do?
3) should it be called on the thread which is running or the object which the thread is running on(access)?
Thanks
Rajesh R
Greenhorn

Joined: Mar 02, 2001
Posts: 12
1) This method is defined in Thread class.
2) An interrupt request is posted for this thread. It need not immediately react to this request. However, if this thread is waiting, it is awakened and it then throws an interrupted exception.
3) It must be called on the thread.

Stevie Kaligis
Ranch Hand

Joined: Feb 04, 2001
Posts: 400
Hi,
for Q#1 :
it defines in java.lang.Thread (see API documentation),
1. void interrupt()
interrupts this thread.
2. static boolean interrupted()
tests whether the CURRENT thread has been interrupted.
3. boolean isInterrupted()
tests whether THIS thread has been interrupted.
for Q#2 and Q#3
imagine this scenario :
you create a thread to perform some work, and then you cancel that work (push cancel button) before it is complete, the scenario may look like this :
Thread 1 :
while (!interrupted()) {
....//perform some work
}
Thread 2 :
if (cancel) {
thread1.interrupt();
}
when thread1 detect that it has been interrupted (using interrupted()), before it stop "perform some work", thread1 will do some cleanup(clears the "interrupted state" of the thread), because it could be affected to another action if the thread is left in the "interrupted state". After that it will responding to the interrupt...(i.e stop "perform some work").
key to remember :
The "interrupted state" of a thread can be cleared only by that thread.
if you try to interrupt "sleep thread" or "wait thread", it will throw InterruptedException, and it will imidietly clears the "interrupted state" of the thread. To handle this situation you can call interrupt() method on catch, for example:
try {
Thread.sleep(sleeptime);
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
the catch clause will re-interrupt the thread.

hope this help.
stevie

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: interrupt method of Thread