如果线程运行时出现异常,
- 我需要打扫卫生还是做其他事情?
- 如果我有数百个线程在运行,我可以使用垃圾收集器来清理我的内存吗?
class MyThread extends Thread {
public void run() {
try {
MyDAO dao = new MyDAO();
List<Results> res = dao.findResults(...);
....
} catch(Exception e) {
//Do I need any clean up here
}
}
}
最佳答案
当 run
方法完成时,无论是正常还是由于异常,它创建的所有对象都可以随意丢弃,不需要进行特定的清理。
您只需要清理需要关闭的资源(数据库连接、文件流等)。此清理通常在 catch
之后的 finally
子句中完成。
public void run(){
Statement statement;
try{
MyDAO dao = new MyDAO(); // doesn't need closing
List<Results> res = dao.findResults(...);
statement = getStatement(); // must be closed
....
} catch (Exception e){
// handle the error
} finally {
if (statement!=null) statement.close();
}
}
关于java - 如果发生异常,Java 线程是否需要清理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16358744/