• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Thread

 
Ranch Hand
Posts: 106
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi ,
I was trying to run the following code in which in the run method i have created another object of the same class(S) & through that i have called met method in that class. i dont understand why the code prints "hi" (in met method)infinitely.If instead of crating another object in run method,i write this.met then code prints "hi" only once.
Can anybody explain me why the code prints "hi " infinitely???


class S implements Runnable
{
S()
{
Thread t=new Thread(this);
t.start();
}

public void run()
{
S d=new S();
this.met();
}

synchronized void met()
{
System.out.println("hi");
}

}
class A
{

public static void main(String[] args)
{
S s=new S();


}
};
 
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Follow the path ... in your main() you create a new S. The constructor starts a new thread. run() creates a new S. The constructor starts a new thread. run() creates a new S. The constructor ... you probably see what's coming, right?
 
venkatesh pendharkar
Ranch Hand
Posts: 106
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi
thanx stan for replying, i now understand why it was happening.It was really a stupid thing to ask that but it actually didn strike me at all while wrinting the code.Nways thaks for helping me.
 
Stan James
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You're welcome! Don't feel stupid, just keep having fun.
reply
    Bookmark Topic Watch Topic
  • New Topic