2016-12-06 73 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