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
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() {} 
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());

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 191 views
+2 votes
1 answer 279 views
+1 vote
0 answers 71 views
0 votes
5 answers 581 views
0 votes
0 answers 82 views
+3 votes
1 answer 768 views
+2 votes
2 answers 799 views
–1 vote
0 answers 145 views

Not a Member yet?

Ask to Folks Login

My Account
446 Folks are online
2 members and 444 guest online
Your feedback is highly appreciated