new Runnable() but no new thread?

sgarg picture sgarg · Jan 27, 2012 · Viewed 106.3k times · Source

I'm trying to understand the code here , specifically the anonymous class

private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
   final long start = mStartTime;
   long millis = SystemClock.uptimeMillis() - start;
   int seconds = (int) (millis / 1000);
   int minutes = seconds / 60;
   seconds     = seconds % 60;

   if (seconds < 10) {
       mTimeLabel.setText("" + minutes + ":0" + seconds);
   } else {
       mTimeLabel.setText("" + minutes + ":" + seconds);            
   }

   mHandler.postAtTime(this,
           start + (((minutes * 60) + seconds + 1) * 1000));
   }
};

The article says

The Handler runs the update code as a part of your main thread, avoiding the overhead of a second thread..

Shouldn't creating a new Runnable class make a new second thread? What is the purpose of the Runnable class here apart from being able to pass a Runnable class to postAtTime?

Thanks

Answer

Wyzard picture Wyzard · Jan 27, 2012

Runnable is often used to provide the code that a thread should run, but Runnable itself has nothing to do with threads. It's just an object with a run() method.

In Android, the Handler class can be used to ask the framework to run some code later on the same thread, rather than on a different one. Runnable is used to provide the code that should run later.