2015-10-22 24 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