0

我有一个用户界面(UI)类。它创建了一些线程(我们称之为 T)来做一些工作。我希望在 T 完成工作时通知我的 UI 类。我想我需要在 UI 类中创建一个事件处理程序(在 onClick() 等中)并从 T 触发它。问题:这可能吗?如何 ?//需要明确的是,UI 类确实已经有一些事件处理程序,这些事件处理程序是由我没有编写的函数触发的。比如 onClick() 等。

4

1 回答 1

0

这是一个相当普遍的要求,因为您通常希望在 UI 线程上做的尽可能少。

如果您使用的是 swing,请查看SwingWorker该类。如果你不使用 swing,你可能想看看ExecutorServiceand 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);
    }
}
于 2013-07-26T14:56:33.467 回答