3

I have recently started digging into Multi-Threading in Java. While exploring things, I discovered there are 2 quick and dirty ways to create Threads "on the go" in Java. Here is the example:

public static void main(String[] args) {
    System.out.println("Thread: " + Thread.currentThread().getName());

    new Thread() {
        public void run() {
            System.out.println("Thread: "
                    + Thread.currentThread().getName());
            System.out.println("hello");
        }
    }.start();

    new Thread(new Runnable() {

        @Override
        public void run() {
            System.out.println("Thread: "
                    + Thread.currentThread().getName());
            System.out.println("hello");
        }

    }).start();
}
  1. First one is the one which starts with new Thread() {
  2. Second one comes after that which starts with new Thread(new Runnable() {

I just wanted to ask if both of the ways are correct? Any difference other than difference of Implementing Runnable Interface v/s Extending Thread class?

Tiny
  • 27,221
  • 105
  • 339
  • 599
Anurag
  • 723
  • 3
  • 13
  • 31

1 Answers1

7

Both ways are acceptable (and neither way is "dirty" in my opinion). The first is less verbose and the one I would prefer in a trivial case like this. If you're extending Thread, so you can also skip Thread.currentThread():

new Thread() {
    public void run() {
        System.out.println("Thread: " + getName());
        System.out.println("hello");
    }
}.start();

In any non-trivial case however (i.e. if the thread does more than just a couple of prints) the usual rule of "favor composition over inheritance" applies which advocates the second approach.

If you're using Java 8, you can even take advantage of the fact that Runnable is a functional interface:

new Thread(() -> {
    System.out.println("Thread: " + Thread.currentThread().getName());
    System.out.println("hello");
}).start()

A final note: I rarely use threads these days. Whenever I do, I tend to end up rewriting it using ExecutorServices.

Community
  • 1
  • 1
aioobe
  • 413,195
  • 112
  • 811
  • 826
  • what do you mean by _less verbose_? – Anurag Nov 30 '14 at 11:09
  • 2
    The first one has been officially discouraged, the reason being exposure to all the `Thread` class's internals which possibly leads to unexpected and unintuitive involvement of lesser-known Java naming resolution rules against members which the programmer isn't even aware of. The general principle behind this is *Favor composition over inheritance*. – Marko Topolnik Nov 30 '14 at 11:10
  • @Anurag, by less verbose I mean less code (since you leave out the `new Runnable()` part). @MarkoTopolnik has a good point regarding composition though. Reformulating my answer slightly. – aioobe Nov 30 '14 at 12:23