我用 swing ui 创建了一个 java 程序。首先,当我单击一个按钮时,我遇到了一个问题,我无法单击另一个按钮。我应该等这个人完成他的任务。所以我创建了一个全局变量线程,并在动作事件中线程执行该方法。如以下代码中所述
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
t = new Thread() {
private int postion;
public void run() {
InstallApk installapk = new InstallApk();
int position = 0;
String fileName = directory;
String shellCommand = fileName;
// for (int position =0; postion < 105;position +5) {
jProgressBar1.setValue(InstallApk.value);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
position += 5;
// }
jProgressBar1.setIndeterminate(true);
installapk.execShellCmd(shellCommand);
System.out.println("la valeur d'execution " + InstallApk.value);
if (InstallApk.value > 3) {
jProgressBar1.setIndeterminate(false);
}
}
};
pid = t.getId();
t.start();
}
我想通过使用其他按钮来停止执行该线程。我试过 t.stop(); t.destroy(); 杀死 pid 但一直以来我都无法停止执行。在我的metod execShellCmd 的实现中,我使用了一个swing worker,但我的问题仍然是如何停止执行。
public static void execShellCmd(String cmd) {
if (runningProcess != null) {
// TODO print some suitable warning about process already running
return;
}
try {
//testPath = getPath();
System.out.println("le chemin de travail.." +testPath);
System.out.println(cmd);
Runtime runtime = Runtime.getRuntime();
process = runtime.exec(new String[] { "sh",
testPath + "/install.sh", cmd });
new SwingWorker<Integer, Void>() {
protected Integer doInBackground() {
// read process output first
BufferedReader buf = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line = "";
try {
while ((line = buf.readLine()) != null) {
System.out.println("exec response: " + line);
log = line;
writeToFile(line);
value ++;
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("la valeur d'execution "+InstallApk.value);
// only once we've run out of output can we call waitFor
while (true) {
try {
return runningProcess.waitFor();
} catch (InterruptedException e) {
// do nothing, wait again
} finally {
Thread.interrupted();
}
}
}
protected void done() {
runningProcess = null;
}
}.execute();
} catch (Exception e) {
System.out.println(e);
}
}