File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

threads

 
prasanthi kothapa
Ranch Hand
Posts: 30
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the code below we are directly calling the
run() method.how is this possible?? i thought
we have to call the start() method in order
to call run()
please explain...

class a1 extends Thread
{
public static void main(String args[])
{
a1 a =new a1();
Thread a11 = new Thread(a);
Thread a12 = new Thread(a);
a11.run();
a12.run();
}
int x=1,y=1;
synchronized void method1()
{
x =x+1;
y=y+1;
}
public void run()
{
for(int i =0 ; i<5;i++)
{
method1();
System.out.println(x+""+y);
}
}
}
 
Harpal Singh
Ranch Hand
Posts: 229
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear prasanthi,
It is very much valid to call run() on thread without calling start()..........but it is not advised to do so........Pls donot ask me why??
Harpal
 
Aparna Narayanan
Ranch Hand
Posts: 44
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
The Java Tutorial says that
"The start method creates the system resources necessary to run the thread, schedules the thread to run, and calls the thread's run method". So, for an orderly processing of the thread, it is better to call start() method than calling the run() method.
Aparna
 
Amit Tyagi
Ranch Hand
Posts: 52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I think Aparna's is write.
You are here just overridding the run() method and calling it as you would have called any normal overridden method.
start() method is neccessary to create the resources....
Thanks Aparna.....

See these type of questions well before sitting for the exam...
All the best to you all..
Amit Tyagi
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic