-1

I am not understanding below program.Runnable is an interface and constructor will not be there in any interface.In this program, how new Runnable(){...} is working?

public class Threads {
    public static void main (String[] args) {
        new Thread(new Runnable() {
            public void run() {
                System.out.print("bar");
        }}).start();    
    }
}
2

4 Answers 4

2

Firstly, what this program is doing is instantiating a new thread from within your main method that prints text to the console.

Now, the Thread class constructor accepts a class that implements the Runnable interface. We can supply a instance to the Thread constructor two ways. We can use a concrete class that implements Runnable or supply an Anonymous Inner Class. In this case you are doing the later.

According to the Oracle Documentation on Anonymous inner classes. Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.

 new Thread(new Runnable() {
     public void run() {
         System.out.print("bar");
     }
 }).start();

So you can think of this as passing a class of the Runnable interface which satisfies the contract by overriding the run method and defining it within the constructor parameter.

Sign up to request clarification or add additional context in comments.

Comments

1

It is creating an instance of anonymous class here:

new Runnable() {

and not of interface Runnable

Comments

1

new Thread() expects a Runnable class. So you are using an anonymous inner class to achieve this. The following is the more verbose way of doing the same thing:

public class Threads {
    public static void main (String[] args) {
        MyRunnable runnable = new MyRunnable();
        Thread thread = new Thread(runnable);
        thread.start();
    }
}

class MyRunnable implements Runnable {
    public void run() {
        System.out.print("bar");
    }
}

Comments

0

Below code instantiates an anonymous inner class for Thread implemented by Runnable interface by overriding run() method. You can refer to this link for in detail stuff on inner classes.

   new Thread(new Runnable() {
public void run() {
System.out.print("bar");
}}).start();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.