简体   繁体   中英

Using Thread interrupt to wake up a thread?

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();
       }
   }
}

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM