use*_*602 1 java swing multithreading
我用swing ui创建了一个java程序.首先,当我点击一个按钮而我无法点击另一个按钮时,我遇到了问题.我应该等到这个完成他的任务.所以我创建了一个全局变量线程,并在action事件中线程执行该方法.如下面的代码中所述
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();
}
Run Code Online (Sandbox Code Playgroud)
我想通过使用其他按钮来停止执行此线程.我试过t.stop(); t.destroy(); 杀死pid,但总是有些结果我不能停止执行.在我的metod execShellCmd的实现中,我使用了一个swing工作者,但我的问题仍然是如何停止执行.
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);
}
}
Run Code Online (Sandbox Code Playgroud)
从您提供的代码中,您可能希望一般性地阅读Swing中的线程,因为听起来问题源于对线程模型的工作方式没有了解.
基本上,你有一个事件调度线程,应该调用所有 Swing操作(SwingUtilities.invokeLater()如果你还没有在这个EDT上使用它).但是,在EDT上根本不应该执行长时间运行的任务,否则(如你所发现的那样)它锁定GUI直到它们完成.
在你想执行一个长时间运行的任务的情况下,你是在正确的行,但你通常使用a SwingWorker,它允许异步执行长时间运行的任务,但在任务完成时还在EDT上提供回调.
在停止这样一个线程方面,一个简单的方法是让它监视一个字段作为执行,并在你希望它停止时从EDT(一个简单的操作)切换该字段.不要使用这种stop()方法或同样的方法,它们有很多问题(它们因为一个很好的理由而被弃用.)如果你正在使用a SwingWorker那么它已经取消了内置的支持,这将是明智的使用.
| 归档时间: |
|
| 查看次数: |
859 次 |
| 最近记录: |