Richard wrote:
> Hi all
>
> I was looking at some code about threads and am a bit stuck. Any advice
> will be appreciated. I have two questions.
>
> First the background....
>
> I have two buttons on a form called one and two. When you click button
> one it outputs the numbers 0 to 99 every tenth of a second. THis is on
> a separate thread. I have a second button which is used to cancel the
> buttonOne action. I have done this with a variable check as recommended
> by Sun in the Thread class file under the stop method
>
> "Many uses of <code>stop</code> should be replaced by code that simply
> modifies some variable to indicate that the target thread should stop
> running. The target thread should check this variable regularly, and
> return from its run method in an orderly fashion if the variable
> indicates that it is to stop running."
>
> And now the questions....
>
> My first question is what happens to this thread when I return from the
> run method? Am I correct in thinking that when the run method of a
> thread is left it goes into the dead state and will just die?
It goes into the terminated state.The Thread object can then be garbage
collected.
> My second question is about the checker boolean that Sun recommends
> using to stop a thread. This works in my example because I am using two
> inner classes so both the start and stop button actions can see the
> 'keepRunning' variable. Is there a pattern or an example of how I
> could do this will three separate classes. I was thinking of passing
> the variable around and checking it but this seemed to have quite a lot
> of coupling. Is there a listener interface I could use for it? Am I
> going along the right lines? Any advice on this would be appreciated
> because I want to try and write **good** code.
You've got to keep it somewhere. You might want to start be
self-encapsulating it with get and set methods, and being explicit which
object you are calling those methods on.
> public class Main extends JFrame{
No need to extend JFrame.
> private boolean keepRunning = true;
You should at least make this variable volatile.
> private class oneAction extends AbstractAction implements Runnable {
Class names should have initial caps. It's a good idea for each class to
only do one thing, so use a separate class for the Runnable.
> public void actionPerformed(ActionEvent e) {
> new Thread(this).start();
> }
Depending upon what you want to do, you may find javax.swing.Timer
useful. In particular, you shouldn't modify the GUI off the Event
Dispatch Thread (EDT).
> Thread.sleep(100);
Sleeping means that the thread can't be told to exit (without an
interrupt, or worse). It's better to wait on a variable.
> } catch (InterruptedException e) {
> e.printStackTrace();
> }
If you've been interrupted, that probably means you should stop what you
are doing. Don't just do the minimum to keep the compiler happy.
Tom Hawtin
--
Unemployed English Java programmer
http://jroller.com/page/tackline/