2015-10-22 85 views
5

這裏的片段:這個中斷()是否必要?

public class LogService { 

    public void stop() { 
     synchronized (this) { isShutdown = true; } 
     loggerThread.interrupt(); /* Is it necesarry? */ 
    } 

    public void log(String msg) throws InterruptedException { 
     synchronized (this) { 
      if (isShutdown) 
      throw new IllegalStateException(...); 
      ++reservations; 
     } 
     queue.put(msg); 
    } 

    private class LoggerThread extends Thread { 
     public void run() { 
      try { 
       while (true) { 
        try { 
         synchronized (LogService.this) { 
          if (isShutdown && reservations == 0) 
           break; 
         } 
         String msg = queue.take(); 
         synchronized (LogService.this) { 
         --reservations; 
         } 
         writer.println(msg); 
        } catch (InterruptedException e) { } /* Do nothing */ 
       } 
      } finally { 
       writer.close(); 
      } 
     } 
    } 
} 

正如上面的代碼,即使我們把LoggerThread.interrupt()在stop()方法,中斷只是被抓線程什麼都不做。

那麼LoggerThread.interrupt()是必要的嗎?

回答

6

是的,它是必要的。如果隊列爲空,則該語句String msg = queue.take();將阻塞,直到元素放入隊列或被中斷。

如果你想保證線程沒有掛起,你需要中斷它。

不過似乎有一個小故障:如果reservations不爲0,當你調用close方法和隊列爲空,似乎你的循環將繼續下去,並在while循環迭代中斷下面就queue.take()掛起。

+1

刪除我的答案是更準確的。 –

+0

所以'InterruptedException'可以傳遞給'queue.take()'? – user2916610

+0

@ user2916610該異常未傳遞給方法 - queue.take()中的代碼檢查線程是否定期中斷,並在線程中斷時拋出InterruptedException。 – assylias