Managing Threads

Managing Threads...


Creating the thread isn't all that hard when it comes down to it. And starting a thread is't exactly rocket science either. The real work is in managing thread(s). This is generally accomplished through the use of a thread manager or caller. Any program can create thread(s), controlling them may not be so easy.

Regardless of how the thread was constructed, when the t.start() method is called the threads run()method is executed. This is the only method that executes in the thread. Other methods may be called from within the run() method, but when this method exits, the thread dies and thread death is no laughing matter.

Thread death is why Java provides the isAlive() method. isAlive() returns true if the thread is still executing the run() method - the only method it was designed to execute. So if isAlive() returns true the thread is alive and the run method is still executing and if it returns false, the thread is dead.

The run() method is generally set up like this...

  • 1: Do some pre-processing or setup work (Initializing)
  • 2: Loop through some processing statements (Running)
  • 3: Do some post-processing or cleanup work (Shut Down)

CREATED 2013-01-07 14:52:56.0

00-19-43

UPDATED 2013-01-08 13:11:41.0

The run Method Loop...


The loop in #2 will probably be most of the threads life, therefore, I prefer to monitor this step seperately. Two things help with this. First a boolean variable labeled isRunning along with its getter method of the same name. Like this...

 public void run(){  // do some pre processing  while(isRunning()){  // do some processing  }  // do some cleanup } 

So if the thread is polled with a call to isRunning(), and that returns true, I know the main loop is still executing and it isn't hung up on a pre or post process. While isAlive indicates that the run method is still executing, isRunning indicates the central loop in the run method is still executing. If isAlive returns true and isRunning returns false then I know it is in the process of shutting down.

In addition I can shut the thread down with a call to the coresponding isRunning(Boolean) method which will set the value of boolean variable isRunning to false and allow the thread to die a natural death. This way I can ensure that any post processing or clean-up is completed before the thread dies.

However, if the thread needed to be abruptly stopped Java provides the interrupt() method. BUT... and there is always a but... the interrupt() method is heavy handed. It will cause an InterruptedException to be thrown. More on that later.

CREATED 2013-01-08 15:24:05.0

00-19-59

UPDATED 2013-01-08 15:25:01.0


CREATED 2013-01-08 14:53:47.0

00-19-54

UPDATED 2013-01-08 14:53:47.0

L
I
N
K
S

DBID: db.wam

Page Server: Ithica

©2019 Leistware.com
        Hello anonymous