1

In java this is valid

new Thread(new Runnable()
    {   
        public void run()
        {
            for(int i=0;i<5;i++)
                System.out.println("From anonymous:"+i);
        }
    }   
).start();

But this is not :

Thread t=new Thread(new Runnable()
    {   
        public void run()
        {
            for(int i=0;i<5;i++)
                System.out.println("From anonymous:"+i);
        }
    }   
).start();

can I achieve it with anonymous class? If yes then How

2
  • 2
    What you want to achieve exactly? start method just runs the thread. And run method does not return any value. Commented Nov 13, 2012 at 7:50
  • I want to call start method with object creation. Commented Nov 13, 2012 at 7:53

3 Answers 3

8

Your code does not work, because it wants to assign the result of the start() method to the variable t. You can do it like so:

Thread t=new Thread(new Runnable()
    {   
        public void run()
        {
            for(int i=0;i<5;i++)
                System.out.println("From anonymous:"+i);
        }
    }   
);
t.start();
Sign up to request clarification or add additional context in comments.

Comments

3

Also, in this case you don't need to use Runnable interface because is implemented by the Thread class.

    new Thread() {
        @Override
        public void run() {
            for(int i=0;i<5;i++)
               System.out.println("From anonymous:"+i);
        }
    }.start();

Comments

1

One thing to note here is that the start method of Thread returns void. This is why you cannot assign it to a variable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.