2013-02-14 60 views
3

我創建了一個ExecutorService來管理每個處理套接字連接的單獨線程。如果套接字當前處於不可中斷的方法(如socketserver.accept()),則線程中斷時,我將覆蓋每個線程中的中斷方法以關閉套接字。ExecutorService沒有正確調用中斷()

如果我手動調用我的線程中斷應用程序時關閉,一切正常關機。但是,如果我使用我的ExecutorService並運行shutdownNow,它似乎根本不會調用重寫的中斷方法。

爲什麼沒有叫我重寫的方法?

+0

你如何讓你的線程進入ExecutorService?你在使用自定義的ThreadFactory嗎? – jtahlborn 2013-02-14 02:12:16

+0

公開您的代碼 – 2013-02-14 02:58:27

+0

我想出了問題。 ExecutorService包裝它作爲參數所需的Runnable,所以這就是爲什麼傳入一個Thread沒有任何作用。奇怪的是,使用一個特殊的close方法創建一個由自定義的ThreadFactory創建的自定義線程,該方法在調用中斷時調用,並將此ThreadFactory傳遞給ExecutorService仍然無效,但我最終取消了它,併爲Runnables創建了一個特殊的隊列不間斷的方法,它們分別清除ExecutorService而不是進一步探測。 – ImpGuard 2013-02-18 18:50:51

回答

0

我有同樣的問題,結果發現使用線程池的解決方案。請參閱下面的說明和簡化代碼。

1)創建了覆蓋中斷()也稱這是使用我創建了一套方法和Closeable接口,配置close()方法我自己的線程類。如果已配置,則重寫interrupt()以調用close方法。

public class CloseableThread extends Thread { 
    private Closeable mCloseable = null; 

    public interface Closeable { 
     void close(); 
    } 

    // Constructors deleted 

    public void interrupt() { 
     super.interrupt(); 
     if (mCloseable != null) { 
      mCloseable.close(); 
     } 
    } 

    public void setCloseable(Closeable closeable) { 
     mCloseable = closeable; 
    } 
} 

2)創建延伸,有一個工廠,我可關閉線程和覆蓋beforeExecute()設置可關閉線程池我自己的游泳池類。

public class CloseableThreadPoolExecutor extends ThreadPoolExecutor { 
    static class CloseableThreadFactory implements ThreadFactory { 
     public Thread newThread(Runnable r) { 
      return (Thread) new CloseableThread(r); 
     } 
    } 

    // Constructors deleted 

    @Override 
    protected void beforeExecute(Thread t, Runnable r) { 
     super.beforeExecute(t, r); 

     if (t instanceof CloseableThread && r instanceof Closeable) { 
      ((CloseableThread) t).setCloseable((Closeable) r); 
     } 
    } 
} 

3)確保使用套接字的任何任務,實現可關閉和close()方法某種原因導致插座關閉。確保乾淨地處理以這種方式關閉時將生成的套接字異常。

相關問題