使用线程中断唤醒线程?

时间:2014-06-26 12:16:51

标签: java android multithreading

使用Thread.interrupt定期唤醒Android上的线程是否有任何缺点。 线程循环看起来类似于:

public void run()
{
   while(true)
   {
       try
       {
          wait();
       }
       catch(InterruptedException e)
       {
          performWork();
       }
   }
}

1 个答案:

答案 0 :(得分:2)

是。这是一种可怕的编码方式。例如,如果线程在I / O中被阻塞而不是像这样被使用,interrupt()将抛出异常。

相反,请使用为此制作的notify/wait。在run()

中有类似的内容
synchronized (this) {
   while (conditionForWaiting) {
      try {
         wait();
      } catch (InterruptedException ex) {}

}
performWork();

并通知线程conditionForWaiting已更改:

synchronized (threadInstance) {
   threadInstance.notify();
}