【问题标题】:Java Monitors -- Catching InterruptedExceptionJava 监视器——捕获 InterruptedException
【发布时间】:2013-10-26 13:41:38
【问题描述】:

我有一个使用 java 实现的监视器

java.util.concurrent.locks.Lock;
java.util.concurrent.locks.ReentrantLock;
java.util.concurrent.locks.Condition;

我要解决的问题是读者/作者问题。我有一个锁lock 和两个条件readerswriters

我注意到Condition.await() 函数抛出InterruptedException。现在,我刚刚用 try / catch 块包围了该方法。但是,catch 块是空的。

我想知道什么时候抛出这个异常以及我应该如何处理它。

readers.await() 在有写入者写入文件/有写入者等待写入文件时调用。

writers.await() 在有一个或多个读取器读取文件或写入器当前正在写入文件时调用。

什么情况下会抛出InterruptedException,应该如何处理?

【问题讨论】:

    标签: java interrupt monitor java.util.concurrent interrupted-exception


    【解决方案1】:

    中断允许在线程上下文中停止一些长/阻塞任务。仅当有人为给定线程设置了“被中断”标志时才会发生 InterruptedException。

    现在关于 await()。当你的线程 A 正在等待 Condition.await() 时,通常这意味着它被停放了

    LockSupport.park(对象拦截器); (-> sun.misc.Unsafe.park(boolean bln, long l) 用于热点)。像这样的:

        public void await() throws InterruptedException {
            if (Thread.interrupted()) {
                throw new InterruptedException();
            }
    
            while (still_waiting) {
                LockSupport.park(this);
                if (Thread.interrupted()) {
                    throw new InterruptedException();
                }
            }
        }
    

    现在让我们假设用户停止了应用程序。主线程调用 A.interrupt() 来完成您的线程 A.interrupt() 在本机 Thread.interrupt0() 中实现。此调用设置线程的“被中断”标志并解除线程 A 的驻留,线程看到它被中断并抛出 InterruptedException。

    如何捕获 InterruptedException 取决于系统要求。如果你的线程在循环中做了一些工作,你应该打破循环让线程完成。此外,如果您刚刚捕获了 InterruptedException,最好为当前线程设置“被中断”标志:

        try {
             ...
             some.await();
         }
         catch (InterruptedException e) { 
             // Restore the interrupted status
             Thread.currentThread().interrupt();
         }
    

    一篇旧文章,但仍然很好:http://www.ibm.com/developerworks/java/library/j-jtp05236/index.html?ca=drs-

    【讨论】:

      猜你喜欢
      • 2013-01-12
      • 2020-07-05
      • 1970-01-01
      • 2012-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多