我花了很多天时间搜索我的java程序的解决方案,但没有结果。 我的程序从jar包中动态加载插件(具有相同接口的类),这些插件不再是向具有不同协议的设备发出请求的线程,其中一些可以被阻止而无法中断它,例如插件设计不当或无限期阻塞I / O请求。我已经阅读了很多关于在循环中使用标志的帖子;在I / O被阻止的情况下关闭套接字,但在我的情况下,我不知道使用什么类型的通信插件,所以我无法提前预测哪种类型的错误可能与被阻塞的线程有关。有没有办法能够在不必完成VM或不必等待它结束阻塞的I / O的情况下停止线程? 这是我的程序所做的(小片段仅概述):
LinkedList<FutureTask<ArrayList<MyObject>>> queue = new LinkedList<FutureTask<ArrayList<MyObject>>>();
FutureTask task = new FutureTask<ArrayList<MyObject>>(data);
/* Foreach task(plugin) insert it into queue*/
/*Sumbit each task in a loop */
executor.submit(queue.get(k));
/*Wait for a specific timeout*/
queue.get(i).get(mTimeout, TimeUnit.MILLISECONDS);
/*catch all type of exception to log errors*/
catch (Exception e)
/*at the end force shutdown BUT IT DOESN'T WORK FOR A BLOCKED THREAD*/
executor.shutdownNow();
并且插件必须扩展此类以与我的应用程序通话:
package com.pack.adapter;
import java.util.ArrayList;
import java.util.concurrent.Callable;
import com.pack.base.MyObject;
public abstract class PluginImpl extends Thread implements Callable<ArrayList<MyObject>> {
protected ArrayList<MyObject> buffer;
public PluginImpl(){
super();
}
@Override
public void interrupt() {
super.interrupt();
}
@Override
public ArrayList<MyObject> call() {
try {
return OnParamsRequest( buffer); //I DON'T KNOW IF THIS FUNC. CAN BLOCK PLUGIN'S THREAD IT'S ABSTRACT FUNCTION
} catch (Exception e) {
if (!isInterrupted()) {
e.printStackTrace();
} else {
Thread.currentThread().interrupt();
System.out.println("Interrupted");
}
}
System.out.println("Shutting down thread "+getPluginName());
return buffer;
}
@Override
public void run() {
if(getName() != null && getName() != ""){
Thread.currentThread().setName(getName());
}
super.run();
}
abstract public void setValues(ArrayList<MyObject> buffer);
abstract public ArrayList<MyObject> OnParamsRequest(ArrayList<MyObject> buffer) throws Exception; //this func. can block for a long time without way to stop this thread...there is way to fix it?
abstract public String getPluginName();
}
有办法阻止它吗?或者有办法摧毁它并避免不同的行为? 谢谢