We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › Threads - testing ifAlive from draw() gives Error
Page Index Toggle Pages: 1
Threads - testing ifAlive from draw() gives Error? (Read 158 times)
Threads - testing ifAlive from draw() gives Error?
Aug 12th, 2009, 3:24am
 
This is a pretty newbie question - I'm trying to delve into the world of threads, but come into problems when I try to do anything with them from within draw() - I get a NullPointerException.  I assume this is something to do with the scope of classes, hopefully, someone can set me straight.

At the top of my program, I define (I assume make public) the instance of my class:

Code:
LoopPlayer thread1; 



Then inside draw(), I start the thread running the first time draw does its loop, then what I want to do is check whether the thread is still alive inside every iteration of the draw() loop, so that if it's died, I can start up a new thread with new parameters:

Code:

void draw()
{
 int firsttime =1;
 if(firsttime==1){
   SimpleThread thread1 = new SimpleThread(groove,randomfreq());
   thread1.start();
   firsttime=0;
 }
 if(thread1.isAlive() == false){
      println("thread 1 is dead");
 }
 ....
}



However, when my program hits the thread1.isAlive(), I get a NullPointerException error.  What am I doing wrong?

Note that one way I tried accomplishing this was to check if the threads are alive within an infinite loop inside the setup function, eg.

Code:

setup(){
 ...
 while(1==1){
   if(thread1.isAlive() == false){
      println("thread 1 is dead");
   }
 }

}
And this works perfectly well!  Except that it's very bad programming practice, and because the program is stuck in setup(), it never gets to draw().

What's going on?  Why can I define and start this thread, but when I try to query .isAlive() from within draw(), it doesn't work?

The class, by the way, is an extension of the Thread class, not the Runnable class.  Whatever that means.  I'm still blindly feeling my way around Java.
Page Index Toggle Pages: 1