2014-07-21 69 views
1

我想在線程死亡之前在最後執行代碼。所以我在尋找的是線程的某種dispose(),tearDown()方法,以確保某些任務在退出線程之前執行。如何在退出線程時執行代碼

+0

id很難說如何改變你的線程,而沒有關於它的信息。例如它是守護線程?它的任務如何?任務是否在無限循環中執行?你現在如何處理線程中斷? – Pshemo

+0

它是threadPoolExecutor中的一個任務,實現爲Runnable – tip

回答

2

你可以用代碼來在自己的代碼一個單獨的線程具有try/finally塊內執行,並從try稱之爲的「真正的」 Runnablerun方法,像這樣:

final Runnable realRunnable = ... // This is the actual logic of your thread 
(new Thread(new Runnable() { 
    public void run() { 
     try { 
      realRunnable.run(); 
     } finally { 
      runCleanupCode(); 
     } 
    } 
})).start(); 

runCleanupCode()的代碼將在用於運行實際線程邏輯的相同線程中執行。

+0

是的,又名'如果您想要函數中的某些代碼最後執行,請將其放在末尾':) –

1

以dasblinkenlight的回答遠一點(太遠):

class ThreadWithCleanup extends Thread { 
    final Runnable main; 
    final Runnable cleanup; 

    ThreadWithCleanup(Runnable main, Runnable cleanup) { 
     this.main = main; 
     this.cleanup = cleanup; 
    } 

    @Override 
    public void run() { 
     try { 
      main.run(); 
     } finally { 
      cleanup.run(); 
     } 
    } 
} 

public class Demo { 
    public static void main(String[] args) { 
     Runnable m = new Runnable() { 
      @Override 
      public void run() { 
       System.out.println("Hello from main."); 
       throw new RuntimeException("Bleah!"); 
      } 
     }; 
     Runnable c = new Runnable() { 
      @Override 
      public void run() { 
       System.out.println("Hello from cleanup."); 
      } 
     }; 
     ThreadWithCleanup threadWithCleanup = new ThreadWithCleanup(m, c); 
     threadWithCleanup.start(); 
     try { 
      threadWithCleanup.join(); 
     } catch (InterruptedException ex) { 
     } 
    } 
} 

我曾經以爲我再也看不到一個正當的理由來擴展Thread類!

2

其他答案沒有考慮到你正在討論線程池。這是你需要做的:

private static class MyThreadFactory implements ThreadFactory { 
    public Thread newThread(final Runnable r) { 
     return new Thread() { 
      public void run() { 
       try { 
        r.run(); 
       } finally { 
        // teardown code 
       } 
      } 
     }; 
    } 

} 
public static void main(String[] args) { 
    ThreadPoolExecutor exec = new ThreadPoolExecutor(10, 20, 100, TimeUnit.SECONDS, null, new MyThreadFactory()); 
} 
相關問題