javamultithreadingswtswt-awt

SWT background thread blocking the GUI


Below code is blocking my UI , I have checked other posts and this seems to be a correct implementation , Please let me know what I am doing wrong here:

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();
            }
        }
    }
}

Solution

  • Well, you use Display.asyncExec(...) in your thread which means the code of Recorder.run() runs in the UI Thread... which of cause will block all the event handling in the UI Thread.

    The basic rule is that the run method must finish within a few milli-seconds!