sur*_*a2k 5 java multithreading garbage-collection
如果在线程的运行时期间存在异常,
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 Code Online (Sandbox Code Playgroud)
当run方法完成时,无论是正常还是由于异常,它创建的所有对象都可以自由地进行,无需进行特定的清理.
您只需要清理需要关闭的资源(数据库连接,文件流等).这种清理通常finally在你的后续条款中完成catch.
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();
}
}
Run Code Online (Sandbox Code Playgroud)