2014-07-21 70 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()); 
} 
相关问题