Hey there! any question in your mind? Ask It Now!.

Popular Categories





Do you know the suitable option to start a thread in Java ??? [poll]

+1 vote
122 views
asked in Java Interview Question by Bhartesh (2,730 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)

2 Answers

0 votes
answered by jess
My choice is : X run = new X(); Thread t = new Thread(run); t.start();
0 votes
answered by Razvan Popovici
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.

Related Questions

0 votes
0 answers 180 views
+2 votes
1 answer 208 views
+1 vote
0 answers 50 views
0 votes
5 answers 514 views
0 votes
0 answers 40 views
+3 votes
1 answer 677 views
+2 votes
2 answers 791 views
–1 vote
0 answers 116 views

Not a Member yet?

Ask to Folks Login

My Account
610 Folks are online
85 members and 525 guest online
Your feedback is highly appreciated