2011-09-25 24 views
0

在我的應用程序代碼中,我擴展了Button視圖(稱爲DigiButton)並覆蓋了onDraw()方法。在onDraw()方法中,我將按鈕文本設置爲某個計數器值。這個計數器值由處理器對象每500毫秒遞減1(我使用Handler.run()方法來更新計數器值)。在Android中執行時使用Handler進行線程互相干擾

現在我在「DigiComponent」類中創建了具有不同初始值計數器的「DigiButton」的兩個實例。 「DigiComponent」有一個按鈕,其onClick事件開始運行這兩個線程。

我看到計數器值更新(在兩個實例上)有一些延遲。我認爲每個線程都會干擾其他線程的執行。爲了確認這一點,我剛開始只運行一個「DigiButton」實例。然後計數器值正確更新。以下是我的代碼:

class DigiButton extends Button{ 

     private int counter; 

     private Runnable handleRunnable; 

     DigiButton(Context context,int val){ 
      super(context); 
      counter = val; 
      initialize(); 
     } 

     private void initialize(int val){ 
      digiHandler = new Handler(); 
      handleRunnable = new Runnable(){ 
      public void run(){ 

      }   
     }; 
     } 

     private void updateCounter(){ 
     counter++; 
     if(counter>0){ 
      runCounter(); 
     } 
     } 


     public void runCounter(){ 
      digiHandler.postDelayed(handleRunnable, 500); 
     } 


     @Override 
    protected void onDraw(Canvas canvas){  
     super.onDraw(canvas);    
     setText(counter); 
    } 


    } 



public class DigiComponent extends Activity implements OnClickListener{ 
    DigiButton thread1, thread2; 

    @Override 
    public void onCreate(Bundle savedInstanceState) {    
     super.onCreate(savedInstanceState); 
     thread1 = new DigiButton(this,30000); 
     thread2 = new DigitButton(this,20000); 
     Button test = new Button(this); 
     LinearLayout layout = new LinearLayout(this); 
     layout.addView(thread1); 
     layout.addView(thread2); 
     layout.addView(test); 
     test.setClickListener(this); 
     setContentView(layout); 
    } 


    public void onClick(View v){ 
    thread1.runCounter(); 
    thread2.runCounter(); 
    } 
} 

是我對線程執行干擾的猜測是否正確?如果是的話如何避免這種情況?我的線程處理代碼有問題嗎?

注意:當我按下「主頁」按鈕退出應用程序並再次打開應用程序時,計數器值更新的延遲更糟。

回答

0

這些不是單獨的線程。這些是預定在主UI線程上運行的Runnable。當您按家時,它會變得更糟,因爲您正在向隊列中添加越來越多的Runnable s(重新安排自己)。

您應該使用AsyncTask.publishProgress或僅使用基本Thread來查看AsyncTask

+0

感謝您的回答。我在我的代碼中嘗試了AsyncTask。 – droidsites