gpt4 book ai didi

JAVA - 从启动器调用时外部 exe 锁定

转载 作者:行者123 更新时间:2023-11-29 05:39:25 25 4
gpt4 key购买 nike

我一直在尝试使用自定义输出流来显示 Jtext 区域上可执行文件的输出。

通过按钮调用可执行文件

        try {
Process p = Runtime.getRuntime().exec("cgminer.exe" + " -o " + Infos.Address + ":" + Infos.Port + " -u " + Infos.User + " -p " + Infos.Password);
p.waitFor();

String line;

BufferedReader error = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while((line = error.readLine()) != null){
System.out.println(line);
}
error.close();

BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((line=input.readLine()) != null){
System.out.println(line);
}

input.close();

OutputStream outputStream = p.getOutputStream();
PrintStream printStream = new PrintStream(outputStream);
printStream.println();
printStream.flush();
printStream.close();
}
catch (Exception e) {
// ...
}
}

}

然后将输出定向到带有

的jtext
public class CustomOutputStream extends OutputStream {
private JTextArea textArea;

public CustomOutputStream(JTextArea textArea) {
this.textArea = textArea;
}

@Override
public void write(int b) throws IOException {
textArea.append(String.valueOf((char) b));
textArea.setCaretPosition(textArea.getDocument().getLength());
}
}

我的问题是当我调用第一个类时按钮锁定并且没有输出到 jtext。只有当我强制关闭 cgminer 时才会出现输出。

非常感谢任何帮助,因为这让我的大脑扭曲了。

最佳答案

My problem is when I call the first class the button locks and no output makes it to the jtext. It is only when I force close the cgminer that the output appears.

这是阻塞 Swing 事件线程的典型症状。当您在 Swing 事件线程(也称为 EDTEvent Dispatch Thread),你阻止线程做它的杂务,包括绘制 GUI 和与用户交互,有效地“卡住”GUI。

解决方案不是像另一个建议那样注释 waitFor(),而是在后台线程(例如 SwingWorker)中运行它和任何其他阻塞代码。当您执行此操作时,请确保只在事件线程上更新您的 Swing GUI。 SwingWorker 具有通过其发布和处理方法执行此操作的内置方法。

详情请查看Concurrency in Swing

您还需要执行更多线程,因为您的某些代码行正在阻塞,并且会阻止下游行运行,直到它们解除阻塞,但到那时所有重要的操作都已完成。例如这些 block :

// this blocks
p.waitFor();

// this blocks both times you use it
while((line = error.readLine()) != null){
System.out.println(line);
}

关于JAVA - 从启动器调用时外部 exe 锁定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18198537/

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