gpt4 book ai didi

java - 从 Java 多线程程序中终止特定线程

转载 作者:行者123 更新时间:2023-12-01 19:25:17 25 4
gpt4 key购买 nike

我正在编写一个 Java 程序,如下所示,该类只是在操作系统级别执行命令。然而,有时我们会遇到程序卡住的问题,因此命令永远不会返回任何状态,因此线程不会终止。

现在我正在尝试增强代码,添加一个额外的东西,我可以在其中杀死特定的线程。我已经捕获了 ThreadId,那么这可行吗?

public class ExecuteCmd implements Runnable {

String ProcessId;
String cmd;
BackendSQL bsql;
Logger myLogger;
Thread myThread;


public ExecuteCmd(String cmd, BackendSQL bsql, String ProcessId, Logger myLogger) {
this.ProcessId=ProcessId;
this.cmd=cmd;
this.bsql=bsql;
this.myLogger=myLogger;
}

public void run() {
int rc = 0;

try {

long ThreadId = Thread.currentThread().getId();


bsql.MarkRunning(ProcessId, ThreadId);

myLogger.debug("[ExecuteCmd] Command is: "+cmd);

String[] cmdFull = cmd.split(";");

Runtime rt = Runtime.getRuntime();

Process p = rt.exec(cmdFull);
myLogger.info("[ExecuteCmd] [Threading] "+ ThreadId + ": Executing command");
myLogger.debug("[ExecuteCmd] Command is: "+cmd);


BufferedReader inStream = new BufferedReader(new InputStreamReader(p.getInputStream()));

String inStreamLine = null;
String inStreamLinebyLine=null;
while((inStreamLine = inStream.readLine()) != null) {
inStreamLinebyLine = inStreamLinebyLine+"\n"+inStreamLine;
}
myLogger.info("Command getInputStream: " + inStreamLinebyLine);



try {
rc = p.waitFor();

if (rc == 0) {
bsql.MarkCompleted(ProcessId);
}else{
bsql.MarkFailed(ProcessId);
}

} catch (InterruptedException intexc) {
System.out.println("Interrupted Exception on waitFor: " +
intexc.getMessage());
}

}catch (IOException IOE) {
myLogger.error("IOException[ExecuteCmd]: " + IOE.getMessage());
}catch (Exception e) {
myLogger.error("Exception[ExecuteCmd]: " + e.getMessage());
}
}

}

最佳答案

您应该将 ExecuteCmd 实例提交到 ExecutorService 。这样,您就可以取消或中断您的任务。

Process#waitFor()是一个可中断的操作,所以它应该可以正常工作。

ExecutorService service = Executors.newSingleThreadedExecutor();
Future<?> future = service.submit(new ExecuteCmd(...));
if (takingTooLong()) {
future.cancel(true);
}

关于java - 从 Java 多线程程序中终止特定线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1566063/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com