参考我之前的问题Unable to perform any action before Process.Runtime.exec statement line,我已将代码更改为两部分,一个线程类 CmdExec 具有执行外部程序的所有代码,如下所示:
public class CmdExec extends Thread
{
private String cmd;
private File path;
public CmdExec() {
}
public CmdExec(String cmd, File path) {
this.cmd = cmd;
this.path = path;
}
public void run(){
try
{
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(cmd , null, path);
InputStream stderr = proc.getErrorStream();
InputStreamReader isr = new InputStreamReader(stderr);
BufferedReader br = new BufferedReader(isr);
String line = null;
System.out.println("<ERROR>");
while ( (line = br.readLine()) != null)
System.out.println(line);
System.out.println("</ERROR>");
int exitVal = proc.waitFor();
System.out.println("Process exitValue: " + exitVal);
} catch (Throwable t)
{
t.printStackTrace();
}
通过参考 jtahlborn 的答案,我还为 GUI 更新目的做了另一个 Runnable 类,如下所示:
Runnable doWorkRunnable = new Runnable() {
public void run() {
System.out.println("hello world");
btnTranscribe.setEnabled(false);
areaOutput.setEditable(false);
areaOutput.setEnabled(false);
areaOutput.setText("Performing segmentation, please wait till process is done\n"); }
};
在实际运行 process.exec() 调用外部程序之前,我调用 SwingUtilities.invokeLater 更改 GUI,如下所示:
SwingUtilities.invokeLater(doWorkRunnable);
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(cmd , null, path);
但是对于上述所有代码,GUI 仍然无法更新,并且仅在该过程完成后才更新。在协调这两个可运行线程和线程的任何特定步骤上我错了吗?
提前感谢您的大力帮助和回答
P / S:我在 GUI 中按下按钮期间开始执行 CmdExec(),如下所示:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
strSegment = "java -Xmx2024m -jar ./LIUM_SpkDiarization-4.2.jar / --fInputMask=" + strAudioOut + "/%s.wav"
+ " --sOutputMask=" + strCtlOut + "/%s.ctl --sOutputFormat=ctl -- doCEClustering --cMinimumOfCluster=1 new3_20110331103858";
CmdExec tryDemo = new CmdExec();
tryDemo = new CmdExec(strSegment, fSegment);
tryDemo.run();
strExtract = "./sphinx_fe -i " + strAudioOut + "/new3_20110331103858.wav"
+ " -o " + strFeatureOut + "/new3_20110331103858.mfc";
//System.out.println (strExtract);
//executeCommand (strExtract, fExtract);
tryDemo = new CmdExec(strExtract, fExtract);
tryDemo.run();
}