Reputation: 5149
Are there any drawbacks to regularly wake up a thread on Android using Thread.interrupt. The thread loop looks similar to this:
public void run()
{
while(true)
{
try
{
wait();
}
catch(InterruptedException e)
{
performWork();
}
}
}
Upvotes: 0
Views: 740
Reputation: 4380
Yes. It's a horrible way to code. interrupt()
will for instance throw an Exception if the Thread is blocked in I/O and is not made to be used like this.
Instead, use notify/wait which is made for this. Something like this in run()
:
synchronized (this) {
while (conditionForWaiting) {
try {
wait();
} catch (InterruptedException ex) {}
}
performWork();
And to notify the thread that conditionForWaiting is changed:
synchronized (threadInstance) {
threadInstance.notify();
}
Upvotes: 2