public void stop(){
setRun(false);
inComingWorkThread.interrupt();
outGoingWorkThread.interrupt();
}
I was trying to stop those thread using interrupt call. And I got an interrupt exception.
public class OutgoingListWorker implements Runnable{
@Override
public void run() {
while(mRunning){
WorkOrder workOrder = getWorkOrder();
//do something
}
}
public synchronized WorkOrder getWorkOrder(){
while(mWorkOrderList.size() == 0){
try {
this.wait();
} catch (InterruptedException e) {e.printStackTrace();}
}
return mWorkOrderList.poll();
}
public synchronized void addWorkOrder(WorkOrder workOrder){
this.notify();
mWorkOrderList.add(workOrder);
}
The problem is getWokrOrder calls wait and if an interrupt happened this time then it won’t kill the thread.. How do I kill the blocked thread safely? Thanks in advance..
I think it’s because you catch the
InterruptedExceptionand continue looping…Exception Handling
There are two ways you could deal with this:
Catch the
InterruptedExceptionoutside of the loop and returnnull.Using this option, you would need to handle the case where
getWorkOrder()returnsnullin yourrun()method:Or secondly, you could just throw
InterruptedExceptionand force yourrun()method to do something about it.Interrupts
As a side note, there is no need to maintain a
mRunningvariable. That is exactly what interrupts do for you!Instead of:
Just write:
And then you don’t even need to call
setRun(false);at all! Here is a good tutorial about interrupts: http://download.oracle.com/javase/tutorial/essential/concurrency/interrupt.html