• Post Reply Bookmark Topic Watch Topic
  • New Topic

Thread

 
venkatesh pendharkar
Ranch Hand
Posts: 106
  • Mark post as helpful
  • send pies
  • 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();


}
};
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • 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
  • 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)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome! Don't feel stupid, just keep having fun.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!