我正在为我的一个朋友写一个小笑话应用程序,我无法弄清楚为什么我的标签没有升级并且GUI冻结了。我知道我必须使用线程进行后台操作才能继续使用GUI,但是在进入线程之前它甚至都会冻结。
Ui课程:
private class CheckButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
check();
}
}
public void check() {
this.jbCheck.setEnabled(false);
this.rand = (int) (Math.random() * 4) + 1;
// Offending lines
this.jlMessage1.setText("");
this.jlMessage2.setText(this.messages.getString("wait_" + this.rand));
this.jlMessage2.setForeground(Color.BLACK);
// End of the offending lines
ExecutorService service = null;
try {
service = Executors.newFixedThreadPool(1);
Future<Integer> task = service.submit(new BackgroundJob());
ping = task.get();
} catch (final InterruptedException ex) {
ex.printStackTrace();
} catch (final ExecutionException ex) {
ex.printStackTrace();
}
this.jlMessage1.setText("Tienes " + ping + " ms de ping.");
if (ping <= 125) {
this.jlMessage2.setText(this.messages.getString("bien_" + this.rand));
this.jlMessage2.setForeground(Color.GREEN);
} else if (ping > 126 && ping <= 200) {
this.jlMessage2.setText(this.messages.getString("medio_" + this.rand));
this.jlMessage2.setForeground(Color.YELLOW);
} else {
this.jlMessage2.setText(this.messages.getString("mal_" + this.rand));
this.jlMessage2.setForeground(Color.RED);
}
service.shutdownNow();
this.jbCheck.setEnabled(true);
}
这是后台工作:
public class BackgroundJob implements Callable<Integer> {
private int ping;
@Override
public Integer call() throws Exception {
ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/c", "ping " + Constants.IP + " | find \"Media\"");
pb.redirectErrorStream(true);
try {
Process p = pb.start();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = br.readLine().trim();
ping = Integer.parseInt(line.split(" ")[8].split("ms")[0]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ping;
}
}
我不知道为什么在调用Future<Integer> task = service.submit(new BackgroundJob());
答案 0 :(得分:0)
GUI不会更改标签,因为您位于&#34; main&#34;线程,负责重新绘制GUI。你打电话
ExecutorService service = null;
try {
service = Executors.newFixedThreadPool(1);
Future<Integer> task = service.submit(new BackgroundJob());
ping = task.get();
以异步方式生成线程。但是呼叫task.get();
再次成为阻止操作。因此,您生成后台线程,但等待阻塞其结果。