We help IT Professionals succeed at work.

starting thread

gudii9
gudii9 asked
on
319 Views
Last Modified: 2012-05-11
>>Which of the following is valid code for starting the execution of a thread

1)

public class TStart extends Thread{
   public static void main(String argv[]){
    TStart ts = new TStart();
    ts.start();
    }
    public void run(){
    System.out.println("Thread starting");
    }
}
2)

public class TStart extends Runnable{
    public static void main(String argv[]){
    TStart ts = new TStart();
    ts.start();
    }
    public void run(){
    System.out.println("Thread starting");
    }
}
3)

public class TStart extends Thread{
    public static void main(String argv[]){
    TStart ts = new TStart();
    ts.start();
    }
    public void start(){
    System.out.println("Thread starting");
    }
}
4)

public class TStart extends Thread{
    public static void main(String argv[]){
    TStart ts = new TStart();
    ts.run();
    }
    public void run(){
    System.out.println("Thread starting");
    }
}
   
   

Answer:

1)

Only option 1 is a valid way to start a new thread executing. The code for option 2 extends Runnable which makes no sense as Runnable is an interface not a class, an interface is used with the implements keyword. The code for option 3 calls the start method directly. If you run this code you will find the text is output but only because of the direct call to the method and not because a new Thread is running. The same is true for option 4, the run method called directly is just another method and will execute like any other.






I have not understood above question and answer clearly from link.
http://www.jchq.net/certkey/0701certkey.htm 
 how the option 4 is not valid answer we are calling start on thread which in turn should call run method as option 1 right.
Comment
Watch Question

Java Developer
CERTIFIED EXPERT
Top Expert 2010
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION

Commented:
Did any of that answer your question?

If so, it is now time to select one or more answers, grade them and close the question.

If not, perhaps a clarifying question would help.
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.