Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

new Runnable() but no new thread?

Tags:

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

like image 240
sgarg Avatar asked Jan 27 '12 06:01

sgarg


People also ask

Does a new runnable create a new thread?

No. new Runnable does not create second Thread .

How do I start a thread inside the run method?

You can create a new thread simply by extending your class from Thread and overriding it's run() method. The run() method contains the code that is executed inside the new thread. Once a thread is created, you can start it by calling the start() method. Thread.


2 Answers

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.

like image 162
Wyzard Avatar answered Oct 02 '22 21:10

Wyzard


If you want to create a new Thread...you can do something like this...

Thread t = new Thread(new Runnable() { public void run() { 
  // your code goes here... 
}});
like image 39
Shashank Kadne Avatar answered Oct 02 '22 22:10

Shashank Kadne