Java Programming - Threads - Discussion

15. 

public class MyRunnable implements Runnable 
{
    public void run() 
    {
        // some code here
    }
}
which of these will create and start this thread?

[A]. new Runnable(MyRunnable).start();
[B]. new Thread(MyRunnable).run();
[C]. new Thread(new MyRunnable()).start();
[D]. new MyRunnable().start();

Answer: Option C

Explanation:

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.


Bharath said: (Jan 26, 2011)  
Super Question!!!

Sidd said: (Dec 7, 2011)  
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.

Shiv said: (Mar 28, 2014)  
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.

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

Ashoka said: (Feb 3, 2015)  
This is good. This is the way creating a thread without creating a object reference.

Ganesh said: (Mar 12, 2015)  
Code should be written before the run method after that we can call the start run method.

Syed said: (Jan 26, 2016)  
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.

Syed said: (Jan 26, 2016)  
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.

Harish said: (Oct 26, 2016)  
Thread t = new Thread(new MyRunnable()).start();

Arati Bonage said: (Mar 7, 2017)  
Very good question. Thanks for posting this. This helps me to improve the technical knowledge.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.