Java – on event dispatch thread – want to leave it

Suppose I have methods that are sometimes called on the event dispatch thread, and sometimes not Now suppose I want some code in this method to call threads other than event scheduling threads

Is there any way to run some code on threads other than EDT at this time?

I tried this:

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

But even if I create a new runnable, mymethod () will eventually run on EDT

Is there any way to run mymethod() on a thread other than EDT at this time?

Solution

You did a good job But your runnable must be passed to a new thread

for example

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

Note that calling the "run()" method does not start a new thread Use start() instead

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

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>