Search code examples
javaandroidmultithreadinghandlerrunnable

regarding threads and runnables


I am having a problem understanding the differences between some kinds of making a tread loop.

one is (a rough demonstration):

Thread thread=new Thread("name") {
public void run()
  {
  // do stuff
  }
}.start();

the second is: making a class that imlpements runnable, creating a thread :

Thread thread = new Thread(this,"name").start();

and the third (in android, i don't if it can work some how else): making a Handler, creating a Runnable, and having handler.postDelayed(runnable), or handler.post(runnable).

I don't understand what's the difference, the only thing i did notice is that making a Thread makes the run loop work a lot faster than using a handler. could some one explain to me what's the difference between them and what should i use to what?


Solution

  • The first and the second way are exactly the same. It is just different constructions that can be more useful in different situations. Note that Thread implements Runnable and may just run himself in the new thread.

    The third way is a little bit misinterpreted by you. Handler runs Runnable in the thread where the Handler was instantiated (unless you specify another looper). If you created your Handler in the UI thread it will run Runnable in the UI thread as well. And as a result it may work slower.