I just found out I could create a new thread with a simple
Thread myThread = new Thread() {
public void run() {}
}
But most books suggest I make a class that extends Thread, which seems a bit too much for me when I can just instantiate the Thread class directly. Is there anything wrong with my way of declaring a new thread over creating a new class?
I would suggest not extending Thread
itself at all. Instead, use the Thread
overload which accepts a Runnable
:
Thread thread = new Thread(new Runnable() {
@Override public void run() {
...
}
});
You're not really changing the behaviour of Thread
- merely giving it some code to run. That's more clearly represented by the code above than by subclassing Thread
.
You should also consider using an ExecutorService
instead of creating threads directly in the first place, mind you. That's another benefit of creating a Runnable
- you're then flexible between passing it to a Thread
constructor or using an ExecutorService
... you can abstract out the Runnable
-creation code, and then use whichever approach you want.
See more on this question at Stackoverflow