3

Suppose that a method I own is sometimes called on the Event Dispatch Thread and is sometimes not. Now suppose some of the code in that method I want to have called on a thread other than the Event Dispatch Thread.

Is there a way to run some code on a thread other than the EDT at this point?

I tried this:

        if (SwingUtilities.isEventDispatchThread()) {
            new Runnable() {
                @Override
                public void run() {
                    myMethod();
                }
            }.run();
        } else {
            myMethod();
        }

But myMethod() ended up running on the EDT even when I created a new Runnable.

Is there a way to run myMethod() on a thread other than the EDT at this point?

Zoyd
  • 3,449
  • 1
  • 18
  • 27
Paul Reiners
  • 8,576
  • 33
  • 117
  • 202
  • You can check the `current thread name`. By default it will be something like `AWT-EventQueue-0` for EDT threads. – Braj Apr 22 '14 at 19:51
  • I know how I can tell that I'm on the AWT Event Queue. The problem is that I'm on it and want some code to run not on the AWT Event Queue. – Paul Reiners Apr 22 '14 at 19:53

1 Answers1

7

You doing it just fine. But your Runnable has to be pass to a new Thread.

e.g.

new Thread(new Runnable() {
 @Override
 public void run() {
     myMethod();
 }
}).start();

Please note that invoking the "run()" method won't start a new Thread. Use start() instead.

See also http://docs.oracle.com/javase/tutorial/essential/concurrency/simple.html

Paul Reiners
  • 8,576
  • 33
  • 117
  • 202
Marcinek
  • 2,144
  • 1
  • 19
  • 25