2016-12-06 106 views
1

抛出我有一个类忽略InterruptedException的从另一个线程

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); 
    } 
} 

然后,我只是跑在我的主

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块。

有时候会抛出异常,但在这种特殊情况下,我并不关心它。

+0

你在哪里添加try-catch块? – user1766169

+0

线程由Runnable构造,而Runnable不能抛出检查异常。 – Sam

+1

不,它不是重复的,因为在单个线程中捕获它是微不足道的。在没有代码重复或糟糕的设计的情况下捕捉它并不是微不足道的。 – marmistrz

回答

1

在此方案中,我定义的接口Interruptible,并且转换的InterruptibleRunnable的方法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 
     } 
    }; 
    } 

} 
1

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

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

有时我们想抛出InterruptedException而不忽略它。这只是我想忽略它的一种情况 – marmistrz