In the code sample you've posted, the
variable "b" will point to a different HeartBeat instance for
every iteration of the loop. If you do not need to maintain a
reference to every HeartBeat instance created in the loop, you
can even use the following code.
for( ;; )
{
new HeartBeat().start();
sleep( 100 );
}
> If I want a program to spawn a thread every few
> minutes, can I
> do something like this?:
>
> for (;;){
> HeartBeat b = new HeartBeat();
> b.start();
> sleep(100);
> }
>
> The class HeartBeat extents Thread.
Well, you do not start an object, you start a thread within an object. It would be more like:
Heartbeat heartbeat = new Heartbeat();
while( true ) {
Thread thread = new Thread( heartbeat );
thread.start();
.... sleep
}
Or if you need you can define a new Heartbeat everytime, and have the Heartbeat constructor starts its own thread automatically everytime:
while( true ) {
Heartbeat heartbeat = new Heartbeat();
....sleep;
}
class Heartbeat implements Runnable {
public Heartbeat(){
Thread myThread = new Thread( this );
myThread.start();
}
public void run() {
... Do stuff ...
}
}
Just a note, if you sleep(100) you'll have 10 thread a second created, and a mess (unless it's your own sleep method...).
Regards,
JFC
> > The class HeartBeat extents Thread.
>
> Well, you do not start an object, you start a thread
> within an object.
You start threads. Threads can be created either by extending Thread (as HeartBeat does) or by giving a Runnable object as a parameter in a suitable constructor of Thread.
E.g.class MyClass extends Thread {
...
}
MyClass t=new MyClass();
t.start();
or
class MyClass implements Runnable {
...
}
Thread t=new Thread(new MyClass());
t.start();
- Marcus
I think you only what to start a new thread every few minutes but want the thread to process the same object every time. If that is the case then do not extend Thread but implement Runnable in class HeartBeat.
HeartBeat h = new HeartBeat();
for (;;){
Thread t = new Thread( h );
t.start();
sleep(100);
}
class HeartBeat implements Runnable{
public void run(){
// do what you want to do repeatedly
}
}