How to start anonymous thread class

JavaMultithreadingAnonymous Class

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

You're already creating an instance of the Thread class - you're just not doing anything with it. You could call start() without even using a local variable:

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

... but personally I'd normally assign it to a local variable, do anything else you want (e.g. setting the name etc) and then start it:

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

Solution 2 - Java

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();

Solution 3 - Java

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.

Solution 4 - Java

Just call start()

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

Solution 5 - Java

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();
    }
}

Solution 6 - Java

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();
    }
}

Solution 7 - Java

Another handy tip for creating Anonymous class which extends Thread class instead of just passing in the Runnable instance or lambda to Thread class's constructor:

  // This also starts the new thread when instantiating the Anonymous class
  // By invoking "this.start()" in a instance initializer block of the Anonymous Thread.
  // Note: We can also override the run from the Thread class itself instead if providing external runnable just in case.
  Thread t = new Thread(()->{}){{start();}};
  
  Runnable r1 = ()->{}; // Runnable Functional Interface lambda format  
  Thread t1 = new Thread(r1){{start();}};

  // Anonymous class which implements Runnable interface
  Runnable r2 = new Runnable(){
    @Override
    public void run(){
      //do some work 
    }
  }
  Thread t2 = new Thread(r2){{start();}};

  // Anonymous class which extends Thread class
  Thread t3 = new Thread(){
    {
       start();
    }
    @Override
    public void run(){
      //do some useful work
    }
  }
  
  class ExtendedThread extends Thread{
    ExtendedThread(){this(null);}
    ExtendedThread(Runnable runnable){
       super(runnable);
       start();
    }
    @Override
    public void run(){
      super.run();
      //do some more useful work always even if there was no runnable was passed via constructor
    } 
  }
  
  Thread t3 = new Thread();

Solution 8 - Java

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.

Solution 9 - Java

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnoMADView Question on Stackoverflow
Solution 1 - JavaJon SkeetView Answer on Stackoverflow
Solution 2 - JavaDunesView Answer on Stackoverflow
Solution 3 - JavaGrayView Answer on Stackoverflow
Solution 4 - JavaJeremiah OrrView Answer on Stackoverflow
Solution 5 - JavarecolicView Answer on Stackoverflow
Solution 6 - JavaDave CostaView Answer on Stackoverflow
Solution 7 - Javamahee96View Answer on Stackoverflow
Solution 8 - JavaentpnerdView Answer on Stackoverflow
Solution 9 - JavaKristoffView Answer on Stackoverflow