Search code examples
javamultithreadinganonymous-class

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?


Solution

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