Topic: 多线程怎么访问SWT

  Print this page

1.多线程怎么访问SWT Copy to clipboard
Posted by: Sunteya
Posted on: 2005-04-05 12:14

在多线程的SWT程序中,线程为什么不能访问SWT控件呢?
下面的代码运行的话会抛出org.eclipse.swt.SWTException: Invalid thread access
要怎么样做 才可以使 多线程可以访问呢?
而没有多线程的话,界面就会失去响应。


import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

public class Test {

  public static void main(String[] args) {
    Display display = Display.getDefault();
    Shell shell = new Shell(display);
    shell.setLayout(new FillLayout());
    final Text t = new Text(shell, SWT.BORDER | SWT.CENTER);

    new Thread(new Runnable() {
      public void run() {
        int i = 0;
        while (true) {
          i++;
          t.setText(String.valueOf(i));
          try {
            Thread.sleep(1000);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
      }
    }).start();

    shell.open();
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch())
        display.sleep();
    }
  }
}


2.Re:多线程怎么访问SWT [Re: Sunteya] Copy to clipboard
Posted by: cnfree
Posted on: 2005-04-05 14:01


display.asyncExec(new Runnable() { // 异步
public void run() {
t.setText(String.valueOfLight Bulb);
}
});

display.syncExec //同步

3.Re:多线程怎么访问SWT [Re: Sunteya] Copy to clipboard
Posted by: Sunteya
Posted on: 2005-04-05 14:08

用asyncExec的话界面会失去响应啊

4.Re:多线程怎么访问SWT [Re: Sunteya] Copy to clipboard
Posted by: Yanjm
Posted on: 2005-04-05 17:40

看看这里对你有没有帮助?

http://www.java2s.com/ExampleCode/SWT-JFace-Eclipse/IllustratesmultithreadUIprogrammingissues.htm

它用了两种方式就是同步和异步,而且同步时界面也正常。

5.Re:多线程怎么访问SWT [Re: Sunteya] Copy to clipboard
Posted by: Sunteya
Posted on: 2005-04-05 21:03

明白了 所有对控件访问的操作 都需要放在display.asyncExec或者syncExec里

谢谢2位了


  public void run() {
    final double pi = calculatePI(9999999);
    display.asyncExec(new Runnable() {
      public void run() {
         theButton.setText("PI = " + pi);
      }
    });
  }


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923