SWT/Swing->线程地狱 [英] SWT/Swing -> Threads n' Hell

查看:97
本文介绍了SWT/Swing->线程地狱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个SWT应用程序.我对SWT感到沮丧,因为它无法轻松完成我想做的事情.所以我用了Swing.摇摆使我的生活变得轻松.耶.除了现在,两人不得不谈谈.问题是,它们运行在不同的线程上,每当我尝试从Swing运行SWT GUI方法时,我都会得到:

I have an SWT application. I was frustrated at SWT for not making it easy to do what I wanted to do. So I used Swing. Swing made my life easy. Yay. Except now, the two have to talk. The issue is, they are running on different threads, and whenever I try to run an SWT GUI method from Swing, I get:

Exception in thread "AWT-EventQueue-0" org.eclipse.swt.SWTException: Invalid thread access

哦,喜悦.那么,我该如何解决呢?如果这是Objective-C,我可以使用:

Oh joy. So, how do I fix this? If this was Objective-C, I could use:

- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait

但是不是,所以我不能.有没有办法在线程B上运行方法A?该线程何时存在?

But it's not, so I can't. Is there no way to run method A on thread B? When that thread is existing?

推荐答案

我在SWT方面工作不多,但似乎SWT会严格禁止在非UI线程中访问SWT对象.您可以将与SWT上的对象对话的请求排队.

I haven't worked much with SWT but it seems that SWT will striclty prohibit accessing an SWT object in the non UI thread. You can queue up a request to talk to an object on the SWT.

链接对此进行了更好的解释

This link explains this better

该示例建议您使用syncExec

The example suggests you to use syncExec

display.syncExec(
  new Runnable() {
    public void run(){
      label.setText(text);
    }
  });

我可以假设这将使Runnable在主SWT UI线程上排队,因此访问是合法的.

This I can assume will queue up the Runnable on the main SWT UI thread and thus the access would be legal.

注意:我再次阅读了该链接,syncExec最终将冻结您的Swing EDT.如果调用syncExec,它将把Runnable放在SWT队列上,并等待其完成.您可以查看asyncEvent,将可运行对象扔到队列中,然后继续工作.

Note: I read over the link again, syncExec will end up freezing your Swing EDT. If you invoke syncExec, it will throw the Runnable on the SWT queue and wait for it to be completed. You can look at asyncEvent to throw the runnable on the queue and continue on working.

这篇关于SWT/Swing->线程地狱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆