3

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

4

3 回答 3

3

您可以将要执行的代码包装在您自己的具有try/finally块的代码中的单独线程中,并从 中调用run“真实”的方法Runnabletry如下所示:

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()将在用于运行实际线程逻辑的同一线程中执行。

于 2014-07-21T18:29:18.897 回答
3

其他答案没有考虑到您正在谈论线程池。这是您需要做的:

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());
}
于 2014-07-21T19:47:40.910 回答
2

将 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 类的正当理由!

于 2014-07-21T18:41:52.980 回答