SWT中的多线程(Invalid thread access)

来源:互联网 发布:酒店网络所需设备清单 编辑:程序博客网 时间:2024/05/26 22:58
最近在学习swt的东西,遇到一个问题,特转录如下。SWT异常: org.eclipse.swt.SWTException: Invalid thread access在创建SWT界面的线程之外的线程中尝试去修改界面元素.将抛出以下异常Exceptioninthread"Thread-0"org.eclipse.swt.SWTException:Invalidthreadaccessatorg.eclipse.swt.SWT.error(SWT.java:2942)atorg.eclipse.swt.SWT.error(SWT.java:2865)atorg.eclipse.swt.SWT.error(SWT.java:2836)上述Thread-0是另外开启的一个线程.【解析】:在SWT程序中,SWT会自动创建一个用户界面线程非用户界面线程不能直接操作用户界面线程要想在另外一个线程中尝试修改用户界面,应采用一下方法:if(!this.display.isDisposed()){Runnablerunnable=newRunnable(){publicvoidrun(){//你改界面的代码}};display.syncExec(runnable);//关键在这一句上(同步调用,等待主界面线程处理完成之后)}swt-doc中的说明:public void syncExec(java.lang.Runnable runnable)Causes the run() method of the runnable to be invoked by the user-interface thread at the next reasonable opportunity. The thread which calls this method is suspended until the runnable completes. Parameters: runnable - code to run on the user-interface thread. (同步调用,需要等待主界面处理完成之后,才能继续)此外,与之对应的另一个方法:public void asyncExec(java.lang.Runnable runnable)Causes the run() method of the runnable to be invoked by the user-interface thread at the next reasonable opportunity. The caller of this method continues to run in parallel, and is not notified when the runnable has completed. Parameters: runnable - code to run on the user-interface thread. (异步调用,不等待主界面线程处理结果)

 

怎么解决SWT多线程错误:Caused by: org.eclipse.swt.SWTException: Invalid thread access我这几天研究JAVA做MSN,下载的示例都是在控制台下显示的,现在要做一个桌面MSN,要在界面上显示运行情况,比如,登录时,在文本框中显示"正在登录,请稍后....",登录成功后显示"登录成功....."等,以及其它一系列事件都要在界面上显示..我用的是SWT Designer来做界面的,界面上有账号和密码输入框,登录及退出按钮,以及显示运行刻录的文本框.现 在只是做了登录,要在文本框里显示登录情况,网上的代码都是通过System.out.println在控制台里显示,而现在我要将记录显示在文本框里, 开始时,我就直接按照调用类方法的办法调,可是总出现Caused by: org.eclipse.swt.SWTException: Invalid thread access这个错误,我查询后知道,这是因为SWT界面线程不能在其它线程里进行操作等.由于以前没做过JAVA桌面程序,也没做过JAVA多线程,所以花了我一天多的时间,都没搞定.下午,在utopian的帮助下,才搞定,太多的道理我也说不清,呵呵,我对JAVA也不是很熟悉,只是在JSP里用到了点皮毛而已.我只说一下我的最后解决方法我就是在那个新线程(其实是一个处理监听事件的接口对象)需要修改界面的地方,那一段代码包起来,比如在我这个MSN的处理对象中,有一个消息是登录成功的消息原来在控制台下显示消息的代码:  /**   * 登录成功后执行该方法   */  public void loginComplete(MsnFriend own) {   System.out.println(own.getLoginName() + " Login OK");    }而想要界面里显示,则改成:  /**   * 登录成功后执行该方法   */  public void loginComplete(MsnFriend own) {    Display.getDefault().syncExec(new Runnable() {    public void run() {    allTxt.setText("登录成功....");    }    });    }开始我只是写了allTxt.setText("登录成功....");这行代码,就一直报那个错,后来,改成       Display.getDefault().syncExec(new Runnable() {    public void run() {    allTxt.setText("登录成功....");    }    });    这样就没问题了,也就是说,在非SWT线程的线程里想要修改SWT界面,都要通过上面类似的办法来做,不然就会报错的呵呵,就是这样,问我为什么,我也说不清,呵呵,也不敢乱说,怕误人子弟啊,如果你知道的话,就详细一点告诉我吧,也让大家来学习和分享你的知识

 

 

 

0 0
原创粉丝点击