Thread interference with each other in their execution (using Handler) in Android
<p>In my App code I've extended the Button view (say it as DigiButton ) and overridden the onDraw() method. In onDraw() method I am setting the button text to some counter value. This counter value is decremented by 1 for every 500 ms by the Handler object (I am using Handler.run() method to update the counter value).</p>

<p>Now I've created two instances of "DigiButton" with different initial values of counter in "DigiComponent" class. "DigiComponent" has a button whose onClick event starts running both the threads.</p>

<p>I see some delay in the counter value update(on both the instances). I thought that each of the thread is interfering with the other thread execution. To confirm this I just started running only one "DigiButton" instance. Then the counter value got updated correct. Below is my code:</p>

<pre><code>   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&gt;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();
   }
 }
</code></pre>

<p>Is that my guess of thread execution interference is correct? If so how to avoid this? Is it something wrong with my thread handling code?</p>

<p>Note: This delay in counter value update is worse when I press "Home" button to go out of the App and I open the App again.</p>
