What is the difference between the two thread calls below? Will the two calls act similarly?
NOTE: I am not using #1 & #2 at the same time, which is the best option.
private void startConnections(){
ServerThread server = new ServerThread();
server.start(); // #1
Thread serverThread = new Thread(server);
serverThread.start(); //#2
}
class ServerThread extends Thread{
public void run(){}
}
The first approach is acceptable, but discouraged. The second one works, but is broken/hard to understand. Consider the third one:
class ServerRunnable implements Runnable {
public void run(){}
}
Runnable run = new ServerRunnable();
Thread serverThread = new Thread(run);
serverThread.start(); //#3
This is pretty common approach - in order to create a new thread you are simply subclassing it and calling start()
method. Many people, including myself, find this idiom being a poor practice - it unnecessarily couples task (contents of run()
method) with threading (Thread
class).
I have never seen code like this and although technically working, I would correct it immediately. Even though you are creating a thread instance, you are passing it to another thread and starting the latter. So why creating the first thread on the first place? Note that Thread
also implements Runnable
, so it technically works, but is really awkward.
So what do I recommend? Implement Runnable
interface that is not coupled to threading. You cannot run Runnable
in a separate thread alone, you have to explicitly create that thread. But having raw Runnable
also allows you to easily switch from native thread to for instance thread-pool.
Technically you can extend Thread
and put such a "runnable" in a thread pool, but this is really hard to understand and you are also unnecessarily carrying Thread
baggage (it is quite a big class).
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