即使启动了新线程,SWT UI也会挂起

时间:2013-09-27 07:28:47

标签: java multithreading swt

我正在使用Display.getDefault().asyncExec()开始一个新线程。线程做了这样的事情:

public void run()
{
    while (! condition)
    {
      //do some processing
      mainWindow.updateStatus(..); //this will call a setText method on a label in 
                    //the original thread
    }
}

然而,当我运行此线程时,程序挂起而不是在标签中顺利显示状态。我做错了什么?

2 个答案:

答案 0 :(得分:4)

你误解了线程的概念。你所谓的线程实际上只是你计划在(UI)线程上执行的一段代码。

通常,UI线程上的代码应该快速执行并尽快返回。您的while循环很可能违反此规则。解决方案是从UI线程中取出循环,即run方法,并将其放在Display.asyncExec()调用周围。

答案 1 :(得分:3)

为了扩展Käärik的答案:你的代码应该是

public class MyTask implements Runnable {
    public void run()
    {
        while (! condition)
        {
            //do some processing without touching the screen
            Display.getDefault().asyncExec(new Runnable() {
                public void run() {
                    mainWindow.updateStatus(..);
                }
            });
        }
    }
}

然后将其作为new Thread(new MyTask())运行,例如在线程池上安排它重复每10秒钟。