0
我有一個用戶界面(UI)類。它創建了一些線程(讓我們稱之爲T)來完成一些工作。我希望我的UI類在T完成工作時得到通知。 我想我需要在UI類(onClick()等)中創建一個事件處理程序,並從T觸發它。 問題:這可能嗎?怎麼樣 ? //要清楚,UI類已經有一些事件處理程序,它們是由我沒寫的函數觸發的。像onClick()等。創建一個新的事件處理程序和源代碼
我有一個用戶界面(UI)類。它創建了一些線程(讓我們稱之爲T)來完成一些工作。我希望我的UI類在T完成工作時得到通知。 我想我需要在UI類(onClick()等)中創建一個事件處理程序,並從T觸發它。 問題:這可能嗎?怎麼樣 ? //要清楚,UI類已經有一些事件處理程序,它們是由我沒寫的函數觸發的。像onClick()等。創建一個新的事件處理程序和源代碼
這是一個相當普遍的要求,因爲您通常希望儘可能少地在UI線程上進行操作。
如果您正在使用鞦韆,請看SwingWorker
課程。如果你不使用鞦韆,你可能想看看ExecutorService
和FutureTask
。
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
public class Futures {
public static void main(String[] args) {
UI ui = new UI();
FutureHandle<String> handle = new FutureHandle<String>(new BigJob());
FutureHandle<String> handle2 = new FutureHandle<String>(new BigJob());
ui.doUIStuff("Things can happen on the UI thread");
ui.startHeavyLiftingJob(handle);
ui.doUIStuff("I've got a big job running, but I'm still responsive");
ui.startHeavyLiftingJob(handle2);
}
/**
* Your UI class. Don't want to do anything big
* on the UI's thread.
*/
static class UI implements Listener<String> {
private ExecutorService threadPool = Executors.newFixedThreadPool(5);
public void doUIStuff(String msg) {
System.out.println(msg);
}
public void startHeavyLiftingJob(FutureHandle<String> handle) {
System.out.println("Starting background task");
handle.setListener(this);
threadPool.execute(handle);
}
public void callback(String result) {
System.out.println("Ooh, result ready: " + result);
}
}
/**
* A handle on a future which makes a callback to a listener
* when the callable task is done.
*/
static class FutureHandle<V> extends FutureTask<V> {
private Listener<V> listener;
public FutureHandle(Callable<V> callable) {
super(callable);
}
@Override
protected void done() {
try {
listener.callback(get());
} catch (InterruptedException e) {
//handle execution getting interrupted
} catch (ExecutionException e) {
//handle error in execution
}
}
public void setListener(Listener<V> listener) {
this.listener = listener;
}
}
/**
* Class that represents something you don't want to do on the UI thread.
*/
static class BigJob implements Callable<String> {
public String call() throws Exception {
Thread.sleep(2000);
return "big job has finished";
}
}
interface Listener<V> {
public void callback(V result);
}
}
您是否聽說過['SwingWorker'](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html)? –
Android,Swing,SWT ..? –