0

下面的代码阻止了我的 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();
            }
        }
    }
}
4

1 回答 1

2

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

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

于 2014-11-08T19:29:15.783 回答