【发布时间】:2012-06-14 05:45:33
【问题描述】:
我开发了一个应用程序,旨在允许用户执行查询。一旦用户输入查询并单击执行按钮,控件就会传递给 RMI 服务器,然后启动线程。
用户应该能够一个接一个地执行其他查询,每个查询将在不同的线程中执行。
我无法停止线程的执行。我想在执行时停止执行,或者根据传递的线程 ID 在按钮单击事件上停止执行。 我正在尝试下面的代码
public class AcQueryExecutor implements Runnable {
private volatile boolean paused = false;
private volatile boolean finished = false;
String request_id="",usrnamee="",pswd="",driver="",url="";
public AcQueryExecutor(String request_id,String usrnamee,String pswd,String driver,String url) {
this.request_id=request_id;
this.usrnamee=usrnamee;
this.pswd=pswd;
this.url=url;
this.driver=driver;
}
public void upload() throws InterruptedException {
//some code
stop();
//some more code
}
public void run() {
try {
while(!finished) {
upload();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void stop() {
finished = true;
}
}
RMI 服务器类从我开始线程的地方
public class ExecutorServer extends UnicastRemoteObject implements ExecutorInterface
{
public ExecutorServer()throws RemoteException
{
System.out.println("Server is in listening mode");
}
public void executeJob(String req_id,String usrname,String pwd,String driver,String url)throws RemoteException
{
try{
System.out.println("Inside executeJob.wew..");
AcQueryExecutor a=new AcQueryExecutor(req_id,usrname,pwd,driver,url);
Thread t1 = new Thread(a);
t1.start();
}
catch(Exception e)
{
System.out.println("Exception " + e);
}
}
public void killJob(String req_id)throws RemoteException{
logger.debug("Kill task");
AcQueryExecutor a=new AcQueryExecutor(req_id,"","","","");
a.stop();
}
public static void main(String arg[])
{
try{
LocateRegistry.createRegistry(2007);
ExecutorServer p=new ExecutorServer();
Naming.rebind("//localhost:2007/exec1",p);
System.out.println ("Server is connected and ready for operation.");
}catch(Exception e)
{
System.out.println("Exception occurred : "+e.getMessage());
e.printStackTrace();
}
}
}
RMI 客户端
ExecutorInterface p=(ExecutorInterface)Naming.lookup("//localhost:2007/exec1");
System.out.println("Inside client.."+ p.toString());
p.executeJob(id, usrname, pswd);
p.killJob(id);
}
直到我的知识 p.killJob() 将不会被调用,直到 executeJob() 完成。 我想在运行时停止执行
【问题讨论】:
-
你如何停止线程?为什么upload()方法中间调用了stop()?
-
我想检查一下在两者之间运行时我可以停止线程,只是为了检查我的停止块是否工作
-
你知道线程在完成
upload()方法之前不会响应任何stop()请求,对吧?您必须轮询upload()方法中的finished标志才能在那里中止。 -
是的,这就是为什么我在上传方法中添加了 stop() ,该方法又将完成标志设置为 true。
-
您正在创建许多不同的
AcQueryExecutor实例,但您没有在其中任何一个上调用a.stop()。您认为哪些stop()消息被忽略了?
标签: java multithreading rmi interrupted-exception