【问题标题】:Ignore InterruptedException thrown from another thread [duplicate]忽略从另一个线程抛出的 InterruptedException [重复]
【发布时间】:2017-04-21 14:50:31
【问题描述】:

我有课

class Foo {
    static void bar() throws InterruptedException {
        // do something
        Thread.sleep(1000);
    }

    static void baz(int a, int b, int c) throws InterruptedException {
        // do something
        Thread.sleep(1000);
    }
} 

然后我只需在我的 main 中运行它

class Main { 
    public static void main() {
        new Thread(Foo::bar).start();
        new Thread(() -> Foo.baz(1, 2, 3)).start();
        new Thread(() -> Foo.baz(1, 2, 3)).start();
    }
}

我不关心InterruptedException。我试图编写一个 try-catch 块,但显然没有捕获到异常。 Java 也不允许我让 main() 抛出。

我怎样才能简单地忽略这个我根本不关心的异常?我不想在每个线程构造函数中都写一个 try-catch 块。

有时应该抛出异常,但在这种特定情况下我不关心它。

【问题讨论】:

  • 你在哪里添加了 try-catch 块?
  • 一个Thread是用Runnable构造的,Runnable不能抛出checked异常。
  • 不,它不是重复的,因为在单个线程中捕获它是微不足道的。并且在没有代码重复或不良设计的情况下多线程捕获它并非易事。
  • 问题有点不同,但接受的答案有一个块可以解决您的确切情况。
  • @marmistrz 如果您想知道如何关闭检查的异常,您不能。可能有一个编译器插件可以有效地改变你使用的语言(比如 Project Lombok)。

标签: java multithreading


【解决方案1】:

在这个解决方案中,我定义了一个接口Interruptible,以及一个将Interruptible 转换为Runnable 的方法ignoreInterruption

public class Foo {

  public static void main(String... args) {
    new Thread(ignoreInterruption(Foo::bar)).start();
    new Thread(ignoreInterruption(() -> Foo.baz(1, 2, 3))).start();
  }

  static void bar() throws InterruptedException {
    // do something
    Thread.sleep(1000);
  }

  static void baz(int a, int b, int c) throws InterruptedException {
    // do something
    Thread.sleep(1000);
  }  

  interface Interruptible {
    public void run() throws InterruptedException;
  }

  static Runnable ignoreInterruption(Interruptible interruptible) {
    return () -> { 
      try {
        interruptible.run();
      }
      catch(InterruptedException ie) {
        // ignored
      }
    };
  }

}

【讨论】:

    【解决方案2】:

    只需在您的方法中捕获异常并忽略它。你永远不会中断线程,所以这很好。

    static void bar() {
        try {
        // do something
        Thread.sleep(1000);
        } catch (InterruptedException ignored) { }
    }
    

    【讨论】:

    • 有时我们想抛出 InterruptedException 而不是忽略它。只是这一种情况我想忽略它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 2016-06-16
    • 2018-07-26
    • 2014-10-09
    • 1970-01-01
    • 2016-07-28
    相关资源
    最近更新 更多