In this article, I wrote about extending a Thread class to create a Thread in java.

We can also use anonymous class to create a Thread. So, this article will cover the part, where we use anonymous class to provide the thread implementation.

If you don’t know, when we declare an anonymous class, it is converted as a class which extends target class or implements target interface.

To convert the code, that I wrote here, into anonymous class, we can write it like this.

This is our Anonymous class .

Thread t = new Thread(){
    @Override
    public void run() {
       System.out.println("Current Thread name :- " + Thread.currentThread().getName());
    }
};

The above code is equivalent to extending Thread class. In useful programs, we won’t ever need to extend or create anonymous class in anyway. We will use high level classes that does all the work for us.

But, it is good to know, all of these. In order to understand the inner workings of the java API.

So, complete java code will look like this.

public class SimpleAnonymoushTread extends Thread {
    public static void main(String ... args) {
        Thread t = new Thread(){
                @Override
                public void run() {
                    System.out.println("Current Thread name :- " + Thread.currentThread().getName());
                }
            };
        t.setName("Simple Anonymous Thread Object" );

        System.out.println("Current thread is - " + Thread.currentThread().getName());
        t.start();
    }
}

Output :-

Current thread is - main
Current Thread name :- Simple Anonymous Thread Object