Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 311
noMAD Avatar asked Mar 08 '12 21:03

noMAD


People also ask

How do I create an anonymous class thread?

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().

Can you instantiate an anonymous class?

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.

How do you start a thread Java?

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.

How do you define anonymous inner class?

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.


1 Answers

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(); 
like image 136
Jon Skeet Avatar answered Nov 07 '22 10:11

Jon Skeet