I have a class named MyThread
which extends the Thread class and implement the run()
function.When I want to run it , I got two ways:
new MyThread().start()
(new Thread(new MyThread)).start();
Anybody can just tell the difference?
start method of thread class is implemented as when it is called a new Thread is created and code inside run() method is executed in that new Thread. While if run method is executed directly than no new Thread is created and code inside run() will execute on current Thread and no multi-threading will take place.
Explanation: run() method is used to define the code that constitutes the new thread, it contains the code to be executed. start() method is used to begin execution of the thread that is execution of run(). run() itself is never used for starting execution of the thread.
There are two ways to create a thread:extends Thread class. implement Runnable interface.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With