1

Is there a more elegant way to do what I'm doing below? That is, is there a more elegant way than polling and sleeping, polling and sleeping, and so on to know when a Runnable.run() method has been called via invokeLater()?

private int myMethod() {
    final WaitForEventQueue waitForQueue = new WaitForEventQueue();
    EventQueue.invokeLater(waitForQueue);
    while (!waitForQueue.done) {
        try {
            Thread.sleep(10);
        } catch (InterruptedException ignore) {
        }
    }

    return 0;
}

private class WaitForEventQueue implements Runnable {
    private boolean done;

    public void run() {
        // Let all Swing text stuff finish.
        done = true;
    }
}
4

3 回答 3

5

更好的方法是使用 a FutureTask(它实现 Runnable 和 Future)并覆盖其 done() 事件以在完成时执行某些操作。

Executor此外,如果它不进行 GUI 操作,而不是使用 AWT EventQueue,则将其作为单独的线程(或使用 )启动。

于 2010-05-10T18:45:00.023 回答
3

如果你想等待,为什么不调用invokeAndWait而不是自己实现呢?

于 2010-05-10T18:38:41.897 回答
0

与其等待线程完成,不如让 UI 显示一个微调器或其他东西,并让线程在完成时调用一个事件。

于 2010-05-10T18:34:51.097 回答