[java] How to start anonymous thread class

I have the following code snippet:

public class A {
    public static void main(String[] arg) {
        new Thread() {
            public void run() {
                System.out.println("blah");
            }
        };
    }
}

Here, how do I call the start() method for the thread without creating an instance of the thread class?

This question is related to java multithreading anonymous-class

The answer is


Since anonymous classes extend the given class you can store them in a variable.

eg.

Thread t = new Thread()
{
    public void run() {
        System.out.println("blah");
    }
};
t.start();

Alternatively, you can just call the start method on the object you have immediately created.

new Thread()
{
    public void run() {
        System.out.println("blah");
    }
}.start();
// similar to new Thread().start();

Though personally, I would always advise creating an anonymous instance of Runnable rather than Thread as the compiler will warn you if you accidentally get the method signature wrong (for an anonymous class it will warn you anyway I think, as anonymous classes can't define new non-private methods).

eg

new Thread(new Runnable()
{
    @Override
    public void run() {
        System.out.println("blah");
    }
}).start();

I'm surprised that I didn't see any mention of Java's Executor framework for this question's answers. One of the main selling points of the Executor framework is so that you don't have do deal with low level threads. Instead, you're dealing with the higher level of abstraction of ExecutorServices. So, instead of manually starting a thread, just execute the executor that wraps a Runnable. Using the single thread executor, the Runnable instance you create will internally be wrapped and executed as a thread.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
// ...

ExecutorService threadExecutor = Executors.newSingleThreadExecutor();
try {
  threadExecutor.execute(
    new Runnable() {
      @Override
      public void run() {
        System.out.println("blah");
      }
    }
  );
} finally {
    threadExecutor.shutdownNow();
}

For convenience, see the code on JDoodle.


The entire new expression is an object reference, so methods can be invoked on it:

public class A {
    public static void main(String[] arg)
    {
        new Thread()
        {
            public void run() {
                System.out.println("blah");
            }
        }.start();
    }
}

Leaving this here for future reference, but its an answer too.

new Thread(() -> whatever()).start();


Add: now you can use lambda to simplify your syntax. Requirement: Java 8+

public class A {
    public static void main(String[] arg)
    {
        Thread th = new Thread(() -> {System.out.println("blah");});
        th.start();
    }
}

Not exactly sure this is what you are asking but you can do something like:

new Thread() {
    public void run() {
        System.out.println("blah");
    }
}.start();

Notice the start() method at the end of the anonymous class. You create the thread object but you need to start it to actually get another running thread.

Better than creating an anonymous Thread class is to create an anonymous Runnable class:

new Thread(new Runnable() {
    public void run() {
        System.out.println("blah");
    }
}).start();

Instead overriding the run() method in the Thread you inject a target Runnable to be run by the new thread. This is a better pattern.


Just call start()

new Thread()
{
    public void run() {
        System.out.println("blah");
    }
}.start();