2013-07-29 81 views
0

我的代碼有多個線程和Runnable。我的問題是我改變了Runnable調用線程中某個變量的值。Android同步線程

在調用之後,我對該變量值進行了檢查,但未檢索到該值。

如何檢索處理後的值?這裏是RunnableThread代碼:

final Runnable r = new Runnable() 
{ 
    public void run() 
    { 
     if(flag==true) 
     onSwipe(); 

     if(SwipeAgain==true) 
     handler.postDelayed(this, 1000); 
    } 
}; 

private void onSwipe() { 

    new Thread() { 
     public void run() { 
      String data = null; 
      decryption_data = null; 
      encryption_data = null; 
      SwipeAgain=false; 
      handler.post(clear_encryption); 
      try { 
       data = sreader.ReadCard(15000); 

      } catch (Exception ex) { 
       if (ex instanceof TimeoutException) { 
        return; 
       } else 
       CloseSinWave(); 
      } 

      if (data == null) { 
       SwipeAgain=true; 
       encryption_data = sreader.GetErrorString(); 
       if (encryption_data.equalsIgnoreCase("cancel all")) 
        return; 
       handler.post(display_encryptiondata); 
      } else { 
       encryption_data = "\n" + data; 
       handler.post(display_encryptiondata); 

    }.start(); 
} 

SwipeAgain是處理

+1

,請在您的清單中刪除無關的代碼,使其更易於閱讀 – ben75

+0

確定我刪除了大部分無關的代碼是這更好 – user2401745

回答

0

後,我想要的值你必須使用CallableRunnable接口不值傳遞給父類的方法。

看到這個example

您可能需要使用Generic對象

0

使用顯示器的最終對象等,並通知其在處理完成。

private final MONITOR Object[] = new Object[0]; 
private AtomicBoolean ready = new AtomicBoolean(false); 

final Runnable r = new Runnable() { 
    public void run() 
    { 
     if(flag==true){ 
      ready.set(false); 
      onSwipe(); 
      synchronized(MONITOR){ 
       if(!ready.get()){ 
        try{ 
         MONITOR.wait(); //will block until it get notified 
        }catch(InteruptedException e){} 
       } 
      } 
     } 
     if(SwipeAgain==true) 
      handler.postDelayed(this, 1000); 
    } 
}; 

private void onSwipe() { 

    new Thread() { 
     public void run() { 
      try{ 
      String data = null; 
      decryption_data = null; 
      encryption_data = null; 
      SwipeAgain=false; 
      handler.post(clear_encryption); 
      try { 
       data = sreader.ReadCard(15000); 

      } catch (Exception ex) { 
       if (ex instanceof TimeoutException) { 
        return; 
       } else 
        CloseSinWave(); 
      } 

      if (data == null) { 
       SwipeAgain=true; 
       encryption_data = sreader.GetErrorString(); 
       if (encryption_data.equalsIgnoreCase("cancel all")) 
        return; 
       handler.post(display_encryptiondata); 
      } else { 
       encryption_data = "\n" + data; 
       handler.post(display_encryptiondata); 
      }finally{ 
       synchronized(MONITOR){ 
        ready.set(true); 
        MONITOR.notifyAll(); //notify (and so unblock r.run()) 
       } 
      } 
    }.start(); 
} 
+0

沒有它不工作我想你說的話,但現在onswip功能不工作 – user2401745

+0

oups ...我忘了塊分隔符。你能再次檢查嗎? – ben75

+0

沒有相同的反應:( – user2401745