我有这个代码: import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;
class Sum implements Runnable{
private int a, b;
public Sum(int a, int b){
this.a = a;
this.b = b;
}
public void run(){
System.out.printf("a + b = %d\t", a+b);
}
}
class Multiply implements Runnable{
private int a, b;
public Multiply(int a, int b){
this.a = a;
this.b = b;
}
public void run(){
System.out.printf("a * b = %d\t", a*b);
}
}
public class HelloWorld{
public static void main(String []args){
ExecutorService executor = Executors.newFixedThreadPool(2);
for (int i = 0; i < 10; i++) {
Runnable worker1 = new Sum(2, 3);
Runnable worker2 = new Multiply(2, 3);
executor.execute(worker1);
executor.execute(worker2);
}
executor.shutdown();
}
}
如果,我用一些文本处理操作替换sum,并与gui的一些更新相乘,就像一个短语没问题,我想立即更新gui,这是在gui应用程序中使用线程的正确方法吗?
答案 0 :(得分:0)
您可以使用线程,但必须在单个用户界面线程上完成对SWT控件的任何访问。
您可以使用Display.asyncExec
(或syncExec
)使用以下内容从其他主题执行此操作:
Display.getDefault().asyncExec(new Runnable() {
public void run() {
// TODO code to change a control
}
});
如果您尝试在后台线程中访问SWT控件,您将收到“无效的线程访问”错误。