225k views
5 votes
Which of these will create and start this thread?

public class MyRunnable implements Runnable
{
public void run()
{
// some code here
}
}

a. new Runnable(MyRunnable).start();
b. new Thread(MyRunnable).run();
c. new Thread(new MyRunnable()).start();
d. new MyRunnable().start();

User Clarise
by
8.5k points

1 Answer

5 votes

Final answer:

The correct option is c. new Thread(new MyRunnable()).start(). To create and start a thread using the Runnable interface, create an instance of MyRunnable and pass it as a parameter to the Thread constructor.

Step-by-step explanation:

The correct option is c. new Thread(new MyRunnable()).start();.

To create and start a thread using the Runnable interface, we need to create an instance of the class that implements the Runnable interface, which is MyRunnable, and then pass it as a parameter to the Thread constructor. Finally, we call the start() method on the newly created Thread object to start the thread execution.

Option a is incorrect because Runnable does not have a constructor that takes MyRunnable as a parameter. Option b is incorrect because it calls the run() method directly on the Thread object instead of starting a new thread. Option d is incorrect because we should create a Thread object and pass the Runnable object as a parameter to its constructor.

User Xiechao
by
8.6k points