• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 310
  • Last Modified:

starting thread

>>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.
0
gudii9
Asked:
gudii9
  • 2
2 Solutions
 
objectsCommented:
option 4 does not call start(). It calls run().
start() must be called to start a new thread
0
 
imladrisCommented:
So, although that code will execute; it will not be executing in a new thread. The original thread will continue executing. There will be a single thread.

In option 1 the original thread starts a new, second, thread, by calling start.
0
 
imladrisCommented:
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.
0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now