views:

78

answers:

3

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;
    }
}
A: 

Instead of waiting for the thread to finish, why not just have the UI display a spinner or something, and have the thread call an event when it is done.

Justin Ethier
Hi Justin, Thanks for the suggestion, but could you be more specific (i.e. show some sample code) as far as the "thread call[ing] an event when it is done" part?
Paul Reiners
+1  A: 

If you want to wait, why not call invokeAndWait rather than implement it yourself?

Yishai
+1  A: 

A better way would be to use a FutureTask (which implements Runnable and Future) and override its done() event to do something when finished.

Also, start this as a separate thread (or use an Executor) if it's not doing GUI manipulation, rather than using the AWT EventQueue.

R. Bemrose