Because you've said your class extends Thread
, the second one is a bit redundant. In your second example, you're not using your class as a Thread
, you're just using it as a Runnable
.
Normally, you'd either extend Thread
and then call its own start
(your #1), or you'd implement Runnable
and then use a Thread
to run it (your #2). But you wouldn't extend Thread
and then use another Thread
to run it.
In terms of what's different, if you need to do anything to control or interrogate the thread, in your first case you'd use the Thread
methods on the instance of your class; in the second case, you'd use them on the instance you create with new Thread
. If you extend Thread
but run it via #2, the Thread
methods on your instance are irrelevant and could be confusing.
That last bit is probably clearer with examples:
Example of extending Thread
:
class Foo extends Thread {
public void run() {
// ...
}
}
// Create it
Foo foo = new Foo();
// Start it
foo.start();
// Wait for it to finish (for example)
foo.join();
Note we started and joined the thread via the foo
reference.
Example of implementing Runnable
:
class Foo implements Runnable {
public void run() {
// ...
}
}
// Create it
Foo foo = new Foo();
// Create a Thread to run it
Thread thread = new Thread(foo);
// Start it
thread.start();
// Wait for it to finish (for example)
thread.join();
Note we started and joined the thread via the thread
reference.
Don't do this:
class Foo extends Thread {
public void run() {
// ...
}
}
// Create it
Foo foo = new Foo();
// Create a Thread to run it -- DON'T do this
Thread thread = new Thread(foo);
// Start it
thread.start();
...because now you have Thread#join
available on both foo
and thread
; which is the right one to use? (The answer is: The one on thread
, but it's confusing, so it's best not to do that.)