How to start anonymous thread class
Asked Answered
P

9

65

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?

Peanuts answered 8/3, 2012 at 21:21 Comment(1)
Java follows liskov substitution principle, so the instance of the anonymous class which you have created is also an instance of Thread.Teriann
R
150

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();
Rashida answered 8/3, 2012 at 21:23 Comment(5)
Whats the difference between the above and creating an implementer inside the thread constructor new Thread( new Runnable() {public void run (){}} );Kennykeno
@Malwaregeek: Well in one case the implementation is a subclass of Thread, and in another case there's an anonymous class implementation of Runnable. They're different, but the difference would usually be irrelevant.Rashida
@Kennykeno Although there may be a slight preference to implement the Runnable interface. See Jon's own answer here.Executioner
@JonSkeet Is it a right approach to refernce an object(of the class that created thread) inside overridden run method?Tradescantia
@uhs: It's fine - do you have a specific concern?Rashida
D
15

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();
Devoted answered 8/3, 2012 at 21:26 Comment(1)
You can also use a lambda expression: new Thread(() -> System.out.println("blah")).Executioner
S
7

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.

Sericeous answered 8/3, 2012 at 21:23 Comment(0)
W
4

Just call start()

new Thread()
{
    public void run() {
        System.out.println("blah");
    }
}.start();
Worthy answered 8/3, 2012 at 21:24 Comment(0)
L
4

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();
    }
}
Lipstick answered 17/12, 2017 at 12:48 Comment(0)
N
3

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();
    }
}
Nilson answered 8/3, 2012 at 21:24 Comment(0)
A
1

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

new Thread(() -> whatever()).start();
Agiotage answered 8/4, 2018 at 12:17 Comment(1)
can you explain what's happening here? is this lambda or some sort of implicit creation of runnable's -> run?Prodigal
H
1

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();
Handful answered 14/4, 2021 at 23:14 Comment(0)
C
0

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.

Cheviot answered 4/1, 2018 at 5:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.