February 17, 2019

Using anonymous class to implement runnable interface in java

You can read about the other ways for implementing runnable interface – using a java class, and using lambda.

In this part, we will use anonymous class for doing this.

In my opinion, at the time of writing this article, the anonymous class is pretty useless now. If you need an anonymus class then use a lambda. 🙂

Java 8 and above have pretty much made everyting that was there in java vserions before Java 8, useless and outdated. I am writing this article for historical reasons. 🙂

Once upon a time, we used something called anonymous class.

In this implementation, we will print the current name of the Thread process.

//Using Anonumous class
Runnable runAnon = new Runnable() {
    @Override
    public void run() {
        String myName = Thread.currentThread().getName();
        System.out.println("MyName :- " + myName);
    }
 };

In the above code anon is an anonumos class. You can compare that code with use of lambda to provide the same implementation.

Now, we will create a Thread object using anonymous class created above.

Thread useAnon = new Thread(runAnon);

Set the name of the thread object created above.

useLambda.setName("Lambda Inside");

Start the thread.

useAnon.start();

The above code can be put inside any method and it will work.

I am going to put inside the main function.

public class SimpleRunnable {

    public static void main(String ... args) {
    //Using Anonumous class
    Runnable runAnon = new Runnable() {
        @Override
        public void run() {
            String myName = Thread.currentThread().getName();
            System.out.println("MyName :- " + myName);
        }
        };
        //Create Thread Object
    Thread useAnon = new Thread(runAnon);
        //Set name of the thread
    useAnon.setName("runAnon");
        //call the start method to put this thread in Runnable stage.
    useAnon.start();
    }
}

OUTPUT

MyName :- runAnon