Reputation: 1274
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
Upvotes: 1
Views: 188
Reputation: 15572
One thing to note here is that the start method of Thread returns void. This is why you cannot assign it to a variable.
Upvotes: 1
Reputation: 31
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();
Upvotes: 3
Reputation: 23665
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();
Upvotes: 8