+1 vote
74.1k views
in Java Interview Question by (2.9k points)

Do you know the suitable option to start a thread ???

class X implements Runnable 
{ 
    public static void main(String args[]) 
    {
        /* Which option will come here? */
    } 
    public void run() {} 
}
Choices:
Thread t = new Thread(X); (0 votes)
Thread t = new Thread(X); t.start(); (0 votes)
X run = new X(); Thread t = new Thread(run); t.start(); (2 votes, 100%)
Thread t = new Thread(); x.run(); (0 votes)
Poll closed

2 Answers

0 votes
by
My choice is : X run = new X(); Thread t = new Thread(run); t.start();
0 votes
by
None of the above, but:

Thread t = new Thread(new X());
t.setDaemon(true);
t.start();

The caveat is that the process will end once the main ends, it will only wait for daemon threads. If the thread is not a daemon, run may be terminated in the middle.

Indeed 3) is the closest good answer, but it is wrong.

* is syntactically incorrect, because X has to be an instance of a Runnable, not a class. Also, the thread is not started.

* is the same as 1), except the thread now starts.

4) Fails to initialize the thread with a runnable (which is allowed, but it won't execute the provided run function). If the thread would be properly constructed, it will yield the desired functionality, however not in a multi-threaded fashion, since calling run directly is legal.

Not a Member yet?

Ask to Folks Login

My Account

Your feedback is highly appreciated