2014-11-08 115 views
0

下面的代碼被擋住了我的UI,我檢查了其他職位,這似乎是一個正確實施,請讓我知道我在做什麼錯在這裏:SWT後臺線程阻塞GUI

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

回答

2

那麼,你在你的線程使用Display.asyncExec(...)這意味着Recorder.run()運行的代碼在UI線程中......哪個原因會阻塞UI線程中的所有事件處理。

基本規則是run方法必須在幾毫秒內完成!