Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/387.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 即使启动了新线程,SWT UI也会挂起_Java_Multithreading_Swt - Fatal编程技术网

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

Java 即使启动了新线程,SWT UI也会挂起,java,multithreading,swt,Java,Multithreading,Swt,我正在使用Display.getDefault.asynceec启动一个新线程。线程执行如下操作: public void run() { while (! condition) { //do some processing mainWindow.updateStatus(..); //this will call a setText method on a label in //the original thre

我正在使用Display.getDefault.asynceec启动一个新线程。线程执行如下操作:

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

但是,当我运行这个线程时,程序挂起,而不是在标签中平滑地显示状态。我做错了什么?

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


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

对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 Threadnew MyTask运行,或者将其安排在线程池中,每10秒重复一次。

Display.asyncExec不会启动新线程。请参阅。@MarttiKärik那么我如何运行一个新线程来更新SWT UI?@MarttiKärik如果我试图从另一个线程访问UI,如果我没有记错的话,这将导致一些线程访问错误。