退出线程时如何执行代码

时间:2014-07-21 18:21:35

标签: java multithreading dispose teardown

我想在线程死之前在最后执行代码。所以我正在寻找的是线程的某种dispose(),tearDown()方法,保证在退出线程之前执行某些任务。

3 个答案:

答案 0 :(得分:3)

您可以将代码包含在您自己的代码中的单独线程中,该代码具有try / finally块,并调用“真实”的run方法{来自Runnable的{​​1}},如下所示:

try

final Runnable realRunnable = ... // This is the actual logic of your thread (new Thread(new Runnable() { public void run() { try { realRunnable.run(); } finally { runCleanupCode(); } } })).start(); 的代码将在用于运行实际线程逻辑的同一线程中执行。

答案 1 :(得分: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());
}

答案 2 :(得分: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类的正当理由!