views:

15285

answers:

11

From what time I've spent with threads in Java, I've found these two ways to write threads.

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


public class ThreadB extends Thread {
    public ThreadB() {
     super("ThreadB");
    }
    public void run() {
     //Code
    }
}
//with a "threadB.start()" call

Is there any significant difference in these two blocks of code?

+3  A: 

I'm not an expert, but I can think of one reason to implement Runnable instead of extend Thread: Java only supports single inheritance, so you can only extend one class.

Edit: This originally said "Implementing an interface requires less resources." as well, but you need to create a new Thread instance either way, so this was wrong.

R. Bemrose
+35  A: 

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 derive from anything else as well.

Jon Skeet
+1. Of course, Jon Skeet doesn't have to mark a thread Runnable. He stares at it, narrows his eyes, and the thread runs for its life.
rtperson
Exactly, well put. What behavior are we trying to overwrite in Thread by extending it? I would argue most people are not trying to overwrite any behavior, but trying to use behavior of Thread.
hooknc
+3  A: 

Instantiating an interface gives a cleaner separation between your code and the implementation of threads, so I'd prefer to implement Runnable in this case.

starblue
+23  A: 

The caveat is important

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. As the javadoc suggests that, if you don't need the returned result, you should consider using this constructor (using "threadA" as you did in the question instead of the "runnable" that they used in the documentation):

new FutureTask<Object>(threadA, null)
Bob Cross
+11  A: 

You should implement Runnable, but if you are running on Java 5 or higher, you should not start it with new Thread but use an ExecutorService instead. For details see: How to implement simple threading in Java.

Fabian Steeg
I wouldn't think ExecutorService would be that useful if you just want to launch a single thread.
R. Bemrose
From what I have learned one should no longer start a thread on your own in general, because leaving that to the executor service makes all much more controllable (like, waiting for the thread to suspend). Also, I don't see anything in the question that implies it's about a single thread.
Fabian Steeg
+4  A: 

One thing that I'm surprised hasn't been mentioned yet is that implementing Runnable makes your class more flexible.

If you extend thread then the action you're doing is always going to be in a thread. However, if you extend Runnable it doesn't have to be. You can run it in a thread, or pass it to some kind of executor service, or just pass it around as a task within a single threaded application (maybe to be run at a later time, but within the same thread). The options are a lot more open if you just use Runnable than if you bind yourself to Thread.

Herms
A: 

Separating the Thread class from the Runnable implementation also avoids potential synchronization problems between the thread and the run() method. A separate Runnable generally gives greater flexibility in the way that runnable code is referenced and executed.

+2  A: 

Moral of the story : Inherit only if you want to override some behavior.

or rather it should be read as "Inherit less, interface more"

panzerschreck
A: 

Runnable because:

  • Leaves more flexibility for the Runnable implementation to extend another class
  • Separates the code from execution
  • Allows you to run your runnable from a Thread Pool, the event thread, or in any other way in the future.

Even if you don't need any of this now, you may in the future. Since there is no benefit to overriding Thread, Runnable is a better solution.

n13
A: 

Leaves more flexibility for the Runnable implementation to extend another class Separates the code from execution Allows you to run your runnable from a Thread Pool, the event thread, or in any other way in the future. Even if you don't need any of this now, you may in the future. Since there is no benefit to overriding Thread, Runnable is a better solution.

Nalawade Tejali
A: 

I would say there is a third way:

public class Something {

    public void justAnotherMethod() { ... }

}

new Thread(new Runnable() {
   public void run() {
    instanceOfSomething.justAnotherMethod();
   }
}).start();

Maybe this is influenced a bit by my recent heavy usage of Javascript and Actionscript 3, but this way your class doesn't need to implement a pretty vague interface like Runnable.

Bart van Heukelom