Я создал программу java с swing ui. во-первых, у меня проблема, когда я нажимаю кнопку, которую я не могу нажать на другую. Я должен подождать, пока он закончит свою задачу. поэтому я создал поток глобальной переменной и в событии действия поток выполнил этот метод. в mintioned в коде нижекак убить нить качанием?
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(); kill pid, но все время какой-то результат я не могу остановить выполнение. в реализации моего метода execShellCmd я использовал качающегося работника, но моя проблема еще в том, как остановить выполнение.
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);
}
}
См. [Как работает SwingWorker] (http://stackoverflow.com/a/11546203/597657). –