我想在线程终止之前在最后执行代码。所以我正在寻找的是某种用于线程的 dispose()、tearDown() 方法,以保证在退出线程之前执行某些任务。
最佳答案
您可以将要在单独线程中执行的代码包装在您自己的代码中,该代码具有 try
/finally
阻止,然后调用run
“真实”的方法Runnable
来自 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();
runCleanupCode()
的代码将在用于运行实际线程逻辑的同一线程中执行。
关于java - 退出线程时如何执行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24872009/