Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

interrupt method of Thread

 
laoniu gougou
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 400
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic