On Event Dispatch Thread---want to get off of it

别来无恙 提交于 2019-12-07 16:32:41

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/23228822/on-event-dispatch-thread-want-to-get-off-of-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!