我编写了一个应用程序,它使用 ExecutorService
运行一些线程并等待它们像这样完成:
ExecutorService exService;
exService = Executors.newCachedThreadPool();
exService.execute(T1);
exService.execute(T2);
exService.shutdown();
boolean finshed = exService.awaitTermination(5, TimeUnit.MINUTES);
有时我需要取消这些线程(整个ExecutorService
)的执行。
我试过 exService.shutdownNow()
但它会抛出 java.lang.InterruptedException
并且不会取消线程。
如何取消这些线程的执行?
编辑:根据 nanda 的要求添加了 T1 类代码
public class TC implements Runnable{
private ExtractedDataBuffer Buffer;
private Scraper scraper;
private String AppPath;
private boolean Succeed=false;
private Map<String,Object> Result=null;
private JLabel StatElement;
public TC(ExtractedDataBuffer Buffer,String AppPath,String XMLfile,JLabel Stat) throws FileNotFoundException {
this.Buffer = Buffer;
this.AppPath=AppPath;
this.StatElement=Stat;
ScraperConfiguration config;
config = new ScraperConfiguration(AppPath + Main.XMLFilesPath +XMLfile);
scraper = new Scraper(config, AppPath);
}
private void extract(){
try{
mainF.SetIconStat("working", this.StatElement);
scraper.execute();
if(scraper.getStatus()==Scraper.STATUS_FINISHED){
this.Succeed=true;
Map<String,Object> tmp=new HashMap<String,Object>();
tmp.put("UpdateTime", ((Variable) scraper.getContext().get("UpdateTime")).toString().trim());
Buffer.setVal(this.Result);
mainF.SetIconStat("done", this.StatElement);
}else{
this.Succeed=false;
this.Result=null;
Buffer.setVal(null);
mainF.SetIconStat("error", this.StatElement);
}
}catch(Exception ex){
this.Succeed=false;
this.Result=null;
Buffer.setVal(null);
mainF.SetIconStat("error", this.StatElement);
}
}
public void run() {
this.extract();
}
}
最佳答案
如果将 shutdown() 更改为 shutdownNow(),则说明您在编写的代码中做了正确的事情。但是,检查 shutdownNow() 的文档:
There are no guarantees beyond best-effort attempts to stop processing actively executing tasks. For example, typical implementations will cancel via Thread.interrupt(), so any task that fails to respond to interrupts may never terminate.
所以您的 T1 和 T2 可能没有以正确的方式编码,并且对中断的响应不够好。您可以为他们复制代码吗?
--
根据你的代码,我猜耗时较长的代码是scraper.execute(),对吧?所以在这些方法中,你必须经常检查这样的东西:
if (Thread.interrupted()) {
throw new InterruptedException();
}
如果中断来了,InterruptedException 将被抛出并在您的 catch 语句中被捕获,线程将停止。
关于java - 如何在java中取消一个ExecutorService,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8023312/