Home > DeveloperSection > Forums > difference between "implements Runnable” and “extends Thread”
Chintoo Semi

Total Post:135

Points:947
Posted on    May-08-2015 1:15 AM

 Java Java  Thread 
Ratings:


 1 Reply(s)
 583  View(s)
Rate this:
From what time I've spent with threads in Java, I've found these two ways to write threads:

With implements Runnable:

public class ThreadA implements Runnable {
    public void run() {
        //Code
    }
}
//Started with a "new Thread(threadA).start()" call
Or, with extends Thread:

public class ThreadB extends Thread {
    public ThreadB() {
        super("ThreadB");
    }
    public void run() {
        //Code
    }
}
//Started with a "threadB.start()" call
Is there any significant difference in these two blocks of code ?


Mayank Tripathi
Mayank Tripathi

Total Post:397

Points:3117
Posted on    May-08-2015 6:43 AM

Yes: implements Runnable is the preferred way to do it, IMO. You're not really specialising the thread's behaviour. You're just giving it something to run. That means composition is the philosophically "purer" way to go.
In practical terms, it means you can implement Runnable and extend from another class as well. Java only supports single inheritance, so you can only extend one class. 

In general, I would recommend using something like Runnable rather than Thread because it allows you to keep your work only loosely coupled with your choice of concurrency. For example, if you use a Runnable and decide later on that this doesn't in fact require it's own Thread, you can just call threadA.run().

Caveat: Around here, I strongly discourage the use of raw Threads. I much prefer the use of Callables and FutureTasks (From the javadoc: "A cancellable asynchronous computation"). The integration of timeouts, proper cancelling and the thread pooling of the modern concurrency support are all much more useful to me than piles of raw Threads.

Follow-up: there is a FutureTask constructor that allows you to use Runnables (if that's what you are most comfortable with) and still get the benefit of the modern concurrency tools. To quote the javadoc:

If you don't need a particular result, consider using constructions of the form:

Future<?> f = new FutureTask<Object>(runnable, null)
So, if we replace their runnable with your threadA, we get the following:

new FutureTask<Object>(threadA, null)
Another option that allows you to stay closer to Runnables is a ThreadPoolExecutor. You can use the execute method to pass in a Runnable to execute "the given task sometime in the future."

If you'd like to try using a thread pool, the code fragment above would become something like the following (using the Executors.newCachedThreadPool() factory method):

ExecutorService es = Executors.newCachedThreadPool();
es.execute(new ThreadA());                                                                       

Don't want to miss updates? Please click the below button!

Follow MindStick