1. SwingUtilities.isEventDispatchThread, 判斷當前線程是不是事件線程。 java
2. SwingUtilities.invokeLater, 能夠將一個Runnable任務調度到事件線程中執行(可在任務線程中調度)。 緩存
3. SwingUtilities.invokeAndWait, 能夠將一個Runnable任務調度到事件線程中執行,並阻塞當前線程直到任務完成(只能從非GUI線程中調用)。 安全
4. 全部Repaint, Revalidation請求插入隊列的方法(任意線程中調用)。 數據結構
5. 全部添加或刪除監聽器的方法(能夠在任務線程中調用,但監聽器自己必定在事件線程中調用)。 框架
private static ExecutorService exec = Executors.newCachedThreadPool(); ... button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { exec.execute(new Runnable() { //執行任務 @Override public void run() { doMuchComptation(); //長時間任務 } }); } });
public void actionPerformed(ActionEvent e) { button.setText("Loading..."); //設置button表現 button.setEnabled(false); exec.execute(new Runnable() { //執行任務 @Override public void run() { try { doMuchComptation(); } finally{ exec.execute(new Runnable() { @Override public void run() { //恢復button表現 button.setText("Load"); button.setEnabled(true); } }); } } }); }
private static ExecutorService exec = Executors.newCachedThreadPool(); private static Future<?> runningTask = null; //任務 startBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (runningTask != null){ runningTask = exec.submit(new Runnable() { @Override public void run() { while (moreWork()){ if (Thread.currentThread().isInterrupted()){//若中斷了 doClean(); break; } doWork(); } } }); } } }); stopBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (runningTask != null){ runningTask.cancel(true); //取消任務 } } });
/** * 支持取消,完成通知及進度通知的任務 */ public abstract class BackgroundTask<T> implements Runnable, Future<T> { private final FutureTask<T> computation = new Computation(); /** * 計算任務 */ private class Computation extends FutureTask<T>{ public Computation() { super(new Callable<T>() { @Override public T call() throws Exception { return BackgroundTask.this.compute(); } }); } @Override protected final void done(){ GuiExecutor.instance().execute(new Runnable() { @Override public void run() { T value = null; Throwable thrown = null; boolean cancelled = false; try { value = get(); } catch (InterruptedException e) { } catch (ExecutionException e) { thrown = e.getCause(); } catch (CancellationException e){ cancelled = true; } finally{ onCompletion(value, thrown, cancelled); } } }); } } protected void setProgress(final int current, final int max){ GuiExecutor.instance().execute(new Runnable() { @Override public void run() { onProgress(current, max); } }); } private void onProgress(int current, int max) {} private void onCompletion(T value, Throwable thrown, boolean cancelled) {} /** * 計算過程 */ protected abstract T compute(); ...//Future其餘方法 }
看到SwingWorker, 其實就如上面的BackGroundTask: ide
public abstract class SwingWorker<T, V> implements RunnableFuture<T> { ...//實現RunnableFuture接口, T: doInBackground返回的結果類型, V: publish, process的參數類型 }使用實例能夠以下:
SwingWorker<String, Integer> worker = new SwingWorker<String, Integer>(){ @Override protected String doInBackground() throws Exception { System.out.println("任務開始"); // do some computation publish(20); publish(30); //... publish(100); return "返回計算結果"; } @Override protected void process(List<Integer> chunks) { //接收publish發送的數據 for (Integer chunk : chunks){ //update ui, for example progress bar System.out.println(chunk); } } @Override protected void done() { System.out.println("任務完成"); // do some state change } }; GuiExecutor.instance().execute(worker); worker.get(); //block to wait results.
不吝指正。 工具