views:

215

answers:

6

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());
+1  A: 

When the new thread is started, it doesn't call the constructor, it would call run(). So no infinite loop here.

Eric Petroelje
A: 

When you pass this, the constructor is not called again.

dsolimano
init() is not a constructor!
fuzzy lollipop
+6  A: 

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.

akf
Actually, as Bozho points out, init() is not a constructor.
R. Bemrose
A: 

Your Constructor doesn't loop forever because t.start(); returns immediately. The body of run() method runs in a different thread.

EDIT : Looks like there is no Constructor involved as others have mentioned. But this logic still holds true.

fastcodejava
Another important reason is that he doesn't have a constructor :)
Fredrik
+2  A: 

this is not the init method, it is the class instance (= the object) being initialized by that method.

So the constructor is not be called anymore implicitly.

A Thread, when started, executes the run() method.

Andrea Zilio
A: 

Since everyone else has covered the new Thread(this) bit, I'll address the other side.

When you start an applet, this is pseudocode for what the applet container does:

Applet applet = new CounterThread();
applet.init();
applet.start();

Since CounterThread has no constructor, Java creates an empty default constructor.

R. Bemrose