0

Is there a difference between

class MyThread extends Thread
{
}

MyThread obj = new MyThread();
Thread t = new Thread(obj);
t.start()

Vs

obj.start()

Is there any advantage in choosing one over other?

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
tez
  • 4,990
  • 12
  • 47
  • 67

6 Answers6

5

In general you should not extend Thread, but implement Runnable instead. Your example would then become:

class MyRunnable implements Runnable {

   public void run() {
      // Whatever needs to be done.
   }
}

MyRunnable obj = new MyRunnable();
Thread t = new Thread(obj);
t.start()
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
3

Yes, there is a difference: you should not extend Thread, but use new Thread(myRunnable). This is similar to your first approach, only your way is misguided in extending Thread instead of implementing Runnable. So do this:

class MyRunnable implements Runnable {
   public void run() { ... }
}

Thread t = new MyThread(new MyRunnable());
t.start();

or, more conveniently,

new Thread(new Runnable() { public void run() {
  ... stuff ...
}}).start();

Be sure to distinguish the concepts of Thread and Runnable: the former is a heavy-weight handle to an actual system resource; the latter is just a holder of a method.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
2

Thread t = new Thread(obj); takes a Runnable obj - the recommended way.

MyThread obj = new MyThread(); requires you to extend Thread which is considered inadvisable nowadays.

See "implements Runnable" vs. "extends Thread" for details on the debate.

Community
  • 1
  • 1
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
1

Your object already extends Thread, so there's no need to wrap it in a new Thread object. If you were implementing Runnable instead, the first approach would be correct.

NilsH
  • 13,705
  • 4
  • 41
  • 59
1

new Thread(obj) delegates Thread.run to obj. This only uses obj as a Runnable and not as a Thread.

MyRunnable obj = new MyRunnable();
Thread t = new Thread(obj);
t.start();

Since (in your code) you are instantiating two threads (one that is started, and one that is never started, you pay some cost for the creation of an additional thread). Aside of this, the form with runnable leads to a better design, since you are not extending Thread for the only purpose of overriding run.

Had you implemented your logic with Runnable, you would be able to use ThreadFactory, and you would not longer be tied to the default implementation of Thread (which comes handy in some situations).

Javier
  • 12,100
  • 5
  • 46
  • 57
1

This seems confusing at best.

I would rather implement the Runnable interface, and then that object can be made available not only to a Thread constructor, but also to thread pools, executors etc. that consume Runnable objects for submission to threads at later times.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440