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:
#1
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 ofrun()method) with threading (Threadclass).#2
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
Threadalso implementsRunnable, so it technically works, but is really awkward.#3
So what do I recommend? Implement
Runnableinterface that is not coupled to threading. You cannot runRunnablein a separate thread alone, you have to explicitly create that thread. But having rawRunnablealso allows you to easily switch from native thread to for instance thread-pool.Technically you can extend
Threadand put such a “runnable” in a thread pool, but this is really hard to understand and you are also unnecessarily carryingThreadbaggage (it is quite a big class).