Reputation: 18068
The thread is working until it is interrupted but it is sleeping from time to time:
public void run() {
while (!Thread.interrupted()) {
//A TASK HERE
try {
Thread.sleep((long) (500 + Math.random() * 100));
} catch (InterruptedException e) {
interrupt(); //it was interrupted while it was sleeping
}
}
}
The intention is to kill the thread by interrupting it. Can I reinterrupt itself like I did or I should set a flag stop = true
within the exception clause?
Upvotes: 3
Views: 71
Reputation: 140318
Catch the interruption outside the loop:
public void run() {
try {
while (true) {
//A TASK HERE
Thread.sleep((long) (500 + Math.random() * 100));
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
Irrespective of where you catch the InterruptedException
, it's a good idea to reinterrupt the current thread if you've not really handled it, and you can't simply throw the InterruptedException
(e.g. because it's inside a method which doesn't declare that it throws InterruptedException
or Exception
or Throwable
).
This allows callers of the run()
method to know that execution was interrupted, so they can stop what they are doing too.
The main case where you may decide not to re-interrupt the thread is if you are writing some sort of threading framework (like Executors), where you reuse the previously-interrupted thread to do the next task.
Upvotes: 6