代码之家  ›  专栏  ›  技术社区  ›  luke

倒计时锁存器中断异常

  •  11
  • luke  · 技术社区  · 14 年前

    我用的是 CountDownLatch 为了在两个线程之间同步初始化进程,我想知道 InterruptedException

    我最初写的代码是:

        private CountDownLatch initWaitHandle = new CountDownLatch(1);
        /**
         * This method will block until the thread has fully initialized, this should only be called from different threads  Ensure that the thread has started before this is called.
         */
        public void ensureInitialized()
        {
            assert this.isAlive() : "The thread should be started before calling this method.";
            assert Thread.currentThread() != this, "This should be called from a different thread (potential deadlock)";
            while(true)
            {
                try
                {
                    //we wait until the updater thread initializes the cache
                    //that way we know 
                    initWaitHandle.await();
                    break;//if we get here the latch is zero and we are done
                } 
                catch (InterruptedException e)
                {
                    LOG.warn("Thread interrupted", e);
                }
            }
        }
    

    这种模式有意义吗?基本上,忽略 中断异常

    为什么会抛出InterruptedException,处理它的最佳实践是什么?

    2 回复  |  直到 7 年前
        1
  •  11
  •   Travelling Man    13 年前

    InterruptedException . 安 中断异常

    IBM发布了一篇关于这一点的好文章: http://www.ibm.com/developerworks/java/library/j-jtp05236.html

    我会这么做:

    // Run while not interrupted.
    while(!(Thread.interrupted())
    {
        try
        {
            // Do whatever here.
        }
        catch(InterruptedException e)
        {
            // This will cause the current thread's interrupt flag to be set.
            Thread.currentThread().interrupt();
        }
    }
    
    // Perform cleanup and exit thread.
    

    这样做的好处是:如果线程在阻塞方法中被中断,中断位将不会被设置,并且 中断异常 interrupt()

        2
  •  3
  •   Enno Shioji    14 年前

    如果您没有预见到 Thread 可能会被打断,想不出任何合理的反应,我认为你应该这样做

     catch (InterruptedException e){
          throw new AssertionError("Unexpected Interruption",e);
     }