问题描述
假设我拥有的方法有时在Event Dispatch Thread上调用,有时则不然。现在假设我想要在除了事件调度线程之外的线程上调用该方法中的一些代码。
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.
有没有办法在线程上运行一些代码除了EDT之外呢?
Is there a way to run some code on a thread other than the EDT at this point?
我试过这个:
if (SwingUtilities.isEventDispatchThread()) {
new Runnable() {
@Override
public void run() {
myMethod();
}
}.run();
} else {
myMethod();
}
但是myMethod()最终在EDT上运行,即使我创建了一个新的Runnable。
But myMethod() ended up running on the EDT even when I created a new Runnable.
有没有办法在EDT以外的线程上运行myMethod()?
Is there a way to run myMethod() on a thread other than the EDT at this point?
推荐答案
你做得很好。但是你的Runnable必须传递给一个新的线程。
You doing it just fine. But your Runnable has to be pass to a new Thread.
例如。
new Thread(new Runnable() {
@Override
public void run() {
myMethod();
}
}).start();
请注意,调用run()方法不会启动新的Thread。改为使用start()。
Please note that invoking the "run()" method won't start a new Thread. Use start() instead.
另请参阅
这篇关于在事件派遣线程---想要离开它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!