Java – Why doesn’t this java program constructor go on infinitely

javamultithreading

Looking at some code, learing about threads:

import java.applet.*;
import java.awt.*;

public class CounterThread extends Applet implements Runnable
{ 
 Thread t; 
 int Count;

 public void init() 
 { 
  Count=0;
  t=new Thread(this);
  t.start();
 }

 public boolean mouseDown(Event e,int x, int y)
 { 
  t.stop();
  return true;
 }

 public void run()
 {
  while(true)
  {
   Count++;
   repaint();
   try {
    t.sleep(10);
   } catch (InterruptedException e) {}
  }
 }

 public void paint(Graphics g)
 {
  g.drawString(Integer.toString(Count),10,10);
  System.out.println("Count= "+Count);
 }

 public void stop()
 {
  t.stop();
 }
}

In the constructor:

public void init()  {   
    Count=0;
    t=new Thread(this);
    t.start();
}

why doesn't this constructor keep going infinitely? it looks like it inits, starts a new thread passing itself which calls the constructor again (I thought), which createds a new thread, etc.

I am missing something fundemental. Thank you for any help

sorry i cannot make the code look right. for some reason when i paste the lines up top don't get in the code parser.

EDIT: Thank you for the answers. For the sake of argument then, to make it an infinite loop would you add this instead:

t=new Thread(new CounterThread());

Best Solution

The passing of this does not call the constructor, it passes a reference. It is a reference to the instance of CounterThread that you are in the process of creating.