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?
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?
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()
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.
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.
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.
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).
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.