2012-11-30 144 views
1

我正在處理我的應用程序中的線程,我面臨線程等待函數的問題。我使用runOnUIThread()創建並顯示了我的UI,我的主要thraed正在等待我的UI線程完成,在thraed完成後,我在主線程中執行了一些處理,問題在於主進程始終處於等待狀態,即使我的線程完成; S的工作,我現在用的等待和notify()功能這個等待和通知在android

 public String LSVerification() { 

     String t = null; 

      t="Sample string"; 
      synchronized(this) 

      { 
      AndroidHTMLActivity.this.runOnUiThread(ShowDialog) ;//here i call my thread 

      try { 
       this.wait();//here i waiting for my thread to finish it's job 

      //here i do some process after my thread finish it's job 
       //the problem is here main process always in wait state 


       } catch (InterruptedException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

      } 
      return t;   
     } 

     private Runnable ShowDialog = new Runnable() { 
      public void run() { 
       String t = null; 
     synchronized(ShowDialog) 

      { 
      Recognition recg=new Recognition(Activity.this); 

       recg.show(); 


      this.notify(); 
      } 

      } 
     }; 
+0

我會syn chronize在同一個對象上的兩個塊,否則你可能有併發訪問 – njzk2

+0

你調用this.notitify,這意味着你通知ShowDialog,而你在這等待着,這是另一個對象。使用1個通用對象來同步,通知和等待。 – njzk2

+0

即使我使用相同的物體,在等待狀態下仍然沒有發生主要過程 –

回答

1

嘗試使用Hanlders執行在後臺工作後更新UI ...

Link to Handlers見下面的代碼..

private void performOperationInBackgroundThread() { 
     Thread Servicethread = new Thread(
        new Runnable() { 
         public void run() { 
          try { 
           PerformThreadOperation(); 
           DataLoaded = true; 
          } catch (Exception e) { 
           ExceptionOccured = true; 
           e.printStackTrace(); 
           System.out.println(e.getMessage()); 
          } 
          handler.sendMessage(handler.obtainMessage()); 
         } 
        } 
        ); 
      Servicethread.start(); 
     } 


static class MyHandler extends Handler{ 
       MyActiviy parentActivity; 
       @Override 
       public void handleMessage(Message msg){ 
        // Update your UI here 

        } 
       } 

       MyHandler(MyActiviy activity){ 
        parentActivity = activity; 
       } 
      } 

MyHandler handler = new MyHandler(this);