我希望在线程结束之前执行一些代码。因此,我正在寻找一种类似于dispose(),tearDown()的方法来确保在线程退出之前执行特定任务。
我希望在线程结束之前执行一些代码。因此,我正在寻找一种类似于dispose(),tearDown()的方法来确保在线程退出之前执行特定任务。
您可以将要执行的代码包装在一个单独的线程中,该线程在您自己的具有try
/finally
块的代码中,并从try
中调用“真正”的Runnable
的run
方法,如下所示:
final Runnable realRunnable = ... // This is the actual logic of your thread
(new Thread(new Runnable() {
public void run() {
try {
realRunnable.run();
} finally {
runCleanupCode();
}
}
})).start();
< p> runCleanupCode()
的代码将在运行实际线程逻辑的同一线程中执行。
其他答案没有考虑到你正在谈论线程池。以下是你需要做的:
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());
}
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类!