如何保证释放Java中ThreadPoolExecutor任务使用的资源
我正在使用ThreadPoolExecutor来共享线程。每次我想要执行IO操作,比如将结果写入文件,我都会使用submit方法来执行runnable。以下是我编写的代码:如何保证释放Java中ThreadPoolExecutor任务使用的资源,java,multithreading,concurrency,java.util.concurrent,Java,Multithreading,Concurrency,Java.util.concurrent,我正在使用ThreadPoolExecutor来共享线程。每次我想要执行IO操作,比如将结果写入文件,我都会使用submit方法来执行runnable。以下是我编写的代码: **ThreadPool class looks like this:** private static ThreadPoolExecutor executors = new ThreadPoolExecutor(8, 16, 25, TimeUnit.SECONDS, new ArrayBlockin
**ThreadPool class looks like this:**
private static ThreadPoolExecutor executors = new ThreadPoolExecutor(8, 16, 25, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(2));;
public static void dispose(){
// end all running queues and destroy this object
executors.shutdown();
executors.shutdownNow();
}
public static void submit(Runnable r){
executors.submit(r);
}
这是WriteFile内部发生的情况:
protected void WriteToFile(Output streamOutput){
try{
// Write to file which can take lots of time
}catch(Exception e){
// print e stack trace
}finally{
streamOutput.close();
}
}
我看到的一些线程表明,shutdownNow()不会阻止任务的停止;相反,它们只是调用.interrupt()。我应该如何使我的Runnabl句柄在写入文件中间中断。然而,我的目标是“确保stremOutput资源每次都关闭”
我应该如何做到这一点 在writeToFile()中打开输出,而不是在构造函数中打开它,然后使用try with resources语句。感谢您的回复,并对响应延迟表示歉意。如果我使用try-with-resource,我应该如何测试我的流是否在线程中断时关闭。用writeToFile()打开输出,而不是在构造函数中打开它,然后使用try-with-resources语句。感谢您的回复,并对响应延迟表示歉意。如果我使用try with资源,我应该如何测试我的流是否在线程中断时关闭。
protected void WriteToFile(Output streamOutput){
try{
// Write to file which can take lots of time
}catch(Exception e){
// print e stack trace
}finally{
streamOutput.close();
}
}