Java Programming - Threads - Discussion

Discussion Forum : Threads - General Questions (Q.No. 4)
4.
class X implements Runnable 
{ 
    public static void main(String args[]) 
    {
        /* Missing code? */
    } 
    public void run() {} 
}
Which of the following line of code is suitable to start a thread ?
Thread t = new Thread(X);
Thread t = new Thread(X); t.start();
X run = new X(); Thread t = new Thread(run); t.start();
Thread t = new Thread(); x.run();
Answer: Option
Explanation:

Option C is suitable to start a thread.

Discussion:
15 comments Page 2 of 2.

Gopichand said:   1 decade ago
I got confused, how it's work please explain it detail.

PRADEEP said:   1 decade ago
The process of working with a thread

1. create an object as here
x run= new x();
2. create a thread and attach an object as here
thread t = new thread(run);
3. start the thread
t.start();

Sundar said:   1 decade ago
@All

The given answer is correct. Don't get confused.

A. Thread t = new Thread(X);

Wrong. Because, here X is the ClassName not an object.

B. Thread t = new Thread(X); t.start();

Wrong. Because, here X is the ClassName not an object. So thread cannot be started. It would have been correct if it was written like:
Thread t = new Thread(new X()); t.start();

D. Thread t = new Thread(); x.run();

Wrong. Here, object 'x' doesn't make any sense.


But, Option C: is correct

X run = new X(); //Creates objects that implements run() as per Runnable interface

Thread t = new Thread(run); // Creates thread

t.start(); // Starts the thread.


Note: The above three statements can be written as simply

(new Thread(new X()).start();

Hope this help you. Have a nice day!

Kaushiki singh said:   1 decade ago
I m also in doubt with this answer I think B option should be the right answer. Can you please give the explaination for this answer.

Tulcram said:   1 decade ago
What does the X stands..?


Post your comments here:

Your comments will be displayed after verification.