File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Simple Doubt with Threads Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Simple Doubt with Threads" Watch "Simple Doubt with Threads" New topic
Author

Simple Doubt with Threads

Gitesh Ramchandani
Ranch Hand

Joined: Feb 28, 2007
Posts: 274
Hi for the following code

public class A extends Thread {

public void run{

System.out.print("RUNNING");
}

public static void main(String[] args) {
A a = new A();
a.start(); //1
a.run(); //2
}

}

My doubt is, both 1 and 2 display RUNNING. so is it not true that calling run will actually call the run method in Thread class?

Regards,
Gitesh
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 35241
    
    7
so is it not true that calling run will actually call the run method in Thread class?


Calling run doesn't "call run", it simply executes the run method. Calling start will in turn lead to the run method being called.

The difference is that calling start will actually start a new thread, while calling run will execute the code in the same thread as the main method runs in.


Android appsImageJ pluginsJava web charts
Gitesh Ramchandani
Ranch Hand

Joined: Feb 28, 2007
Posts: 274
Originally posted by Ulf Dittmer:


Calling run doesn't "call run", it simply executes the run method. Calling start will in turn lead to the run method being called.

The difference is that calling start will actually start a new thread, while calling run will execute the code in the same thread as the main method runs in.


So if I'm asked in which case (out of 1 and 2) will a new thread of execution start, my answer should be a.start(); //1. Am i correct now?
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 35241
    
    7
Yes.
Gitesh Ramchandani
Ranch Hand

Joined: Feb 28, 2007
Posts: 274
Thanks.
Manfred Klug
Ranch Hand

Joined: Jun 04, 2007
Posts: 377
Hi Gitesh,

you can see the difference if you modify the sample a little bit.
Gitesh Ramchandani
Ranch Hand

Joined: Feb 28, 2007
Posts: 274
Originally posted by Manfred Klug:
Hi Gitesh,

you can see the difference if you modify the sample a little bit.


Thanks Manfred,

I see that when run() is directly called, no new thread is created. Only by calling start a new thread is created.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Simple Doubt with Threads
 
Similar Threads
Thread Doubt
Doubt
Thread Doubt
Doubt in Threads Synchronization
Doubt in Threads????