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?
The first way is to extend the Thread class, override the run() method with the code you want to execute, then create a new object from your class and call start(). The second method is to pass an implementation of the Runnable interface to the constructor of Thread, then call start().
Anonymous classes are inner classes with no name. Since they have no name, we can't use them in order to create instances of anonymous classes. As a result, we have to declare and instantiate anonymous classes in a single expression at the point of use.
To start the Java thread you will call its start() method, like this: thread. start(); This example doesn't specify any code for the thread to execute.
Java anonymous inner class is an inner class without a name and for which only a single object is created. An anonymous inner class can be useful when making an instance of an object with certain "extras" such as overloading methods of a class or interface, without having to actually subclass a class.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With