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
#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 of run()
method) with threading (Thread
class).
#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 Thread
also implements Runnable
, so it technically works, but is really awkward.
#3
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).
And Thread must be used to run the Runnable Object. Is my understanding correct? – sravanreddy001 Mar 10 '12 at 19:41