阻止GUI的SWT后台线程

时间:2014-11-08 19:22:21

标签: java multithreading swt swt-awt

下面的代码阻止了我的UI,我检查了其他帖子,这似乎是一个正确的实现,请让我知道我在做错了什么:

public class RecordTest {

    public static boolean stopFlag=false;
    public static void main(String[] args) {

         Display display = Display.getDefault();
        Shell shell = new Shell (display);
        Label label = new Label (shell, SWT.NONE);
        label.setText ("Enter your URL:");
        final Text text = new Text (shell, SWT.BORDER);
        text.setLayoutData (new RowData (100, SWT.DEFAULT));
        Button ok = new Button (shell, SWT.PUSH);
        ok.setText ("Start Record");

        Thread updateThread = new Thread() {
        public void run() {
            Display.getDefault().asyncExec(new Recorder(stopFlag));
        }
    };
    // background thread
    updateThread.setDaemon(true);
    updateThread.start();



        ok.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                System.out.println("Start Record");

            }
        });
        Button cancel = new Button (shell, SWT.PUSH);
        cancel.setText ("Stop Recording");
        cancel.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                System.out.println("Stop Recording");
                stopFlag=true;
            }
        });
        shell.setDefaultButton (cancel);
        shell.setLayout (new RowLayout ());
        shell.pack ();
        shell.open ();
        while (!shell.isDisposed ()) {
            if (!display.readAndDispatch ()) display.sleep ();
        }
        display.dispose ();
    }
}

------------------------------------ Recorder.java -------- ---------------------------------

public class Recorder implements Runnable {

    private boolean stopFlag = false;

    public Recorder(boolean stopFlag) {
        this.stopFlag = stopFlag;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                System.out.println("Waiting ....");
                Thread.sleep(3000);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

好吧,你在你的线程中使用Display.asyncExec(...),这意味着Recorder.run()的代码在UI线程中运行......其中的原因将阻止UI线程中的所有事件处理。

基本规则是run方法必须在几毫秒内完成!