SWT多線程-關於非UI線程操作UI線程(一)

最近在使用SWT開發桌面程序。

在開發的過程中需要實現通過一個線程實時讀取系統時間並能刷新界面上的時間顯示。

 

使用如下代碼實現:

1、創建一個Runnable

   //系統時間
   final Runnable timer = new Runnable()
   {
    public void run()
    {
     synchronized (this) {
      try {
         DateFormat d1 = DateFormat.getDateTimeInstance();          String str1 = d1.format(new Date());      
         shell.getStatusbarLabel().setText(str1);
      } catch (Exception e) {
       // TODO: handle exception
      }
     }
    }
   };

2、在代碼中加入如下語句,其中timerExec爲主線程中實現timer,並設定時間爲主線城啓動後0秒後執行。

   while (!shell.isDisposed()) {
    if (!display.readAndDispatch())
     display.sleep();
    else    
      display.timerExec(0,timer);        
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章