Java Programming - Threads - Discussion

Discussion Forum : Threads - General Questions (Q.No. 15)
public class MyRunnable implements Runnable 
    public void run() 
        // some code here
which of these will create and start this thread?
new Runnable(MyRunnable).start();
new Thread(MyRunnable).run();
new Thread(new MyRunnable()).start();
new MyRunnable().start();
Answer: Option

Because the class implements Runnable, an instance of it has to be passed to the Thread constructor, and then the instance of the Thread has to be started.

A is incorrect. There is no constructor like this for Runnable because Runnable is an interface, and it is illegal to pass a class or interface name to any constructor.

B is incorrect for the same reason; you can't pass a class or interface name to any constructor.

D is incorrect because MyRunnable doesn't have a start() method, and the only start() method that can start a thread of execution is the start() in the Thread class.

10 comments Page 1 of 1.

Arati bonage said:   6 years ago
Very good question. Thanks for posting this. This helps me to improve the technical knowledge.

Harish said:   7 years ago
Thread t = new Thread(new MyRunnable()).start();

Syed said:   7 years ago
No need of writing before the run method it is a method we can write anywhere. Whenever we call the start method it directly calls the run method.

Syed said:   7 years ago
It not need to write before the run method. Because methods can be write any where and until we can't call the method it not going to to execute.

And one more thing in threads that whenever we create thread object and call the start method it directly/default start method call the run method. To call the run method we have to call start method.

Ganesh said:   8 years ago
Code should be written before the run method after that we can call the start run method.

Ashoka said:   8 years ago
This is good. This is the way creating a thread without creating a object reference.

Chinmoy said:   9 years ago
Yes, option 3 has to be written outside run(), because start() calls the run(), if its inside run(), then how it will be called.

Shiv said:   9 years ago
I think the code should be written before run method.

Means new Thread(new MyRunnable()).start();

Should be before run method to start the run method.

Sidd said:   1 decade ago
This is a basic property of implementing Runnable interface.

First we have to create Thread class object then this created object passes to own class object as argument.

Bharath said:   1 decade ago
Super Question!!!

Post your comments here:

Your comments will be displayed after verification.