Copyright (c) SEMM NL All rights reserved.
Author : Paul Hamaker. Part of JavaLessons.com

Essential.

A java.lang.Thread is used .

Instance is created ....

and started .

Now the thread goes about its business in the run method,....

but MEANWHILE the main thread continues here. So now you have two threads running. ( Actually more, in the background )

The thread has entered the run method, because it has received a reference to this applet instance, when it was created :

The applet is known to contain this run method, because it implements the Runnable interface.

The task thread makes an array of Colors and creates a reference to itself .

It enters the loop, because both references refer to this thread :

This evaluates to TRUE, if NOT pause, if NOT FALSE, that is.

This statement ensures that i never has another value than 0, 1 or 2 at this point ,....

so we'll always have a valid index into the Color array.

The applet's colour is set and the thread goes to sleep for one second at the most .

Whatever this thread is doing, the applet can handle mouse events, because there's yet another thread taking care of this.

So, if there's a click on the applet, the mouseClicked method is called and the boolean is reversed, so if it's FALSE, it becomes TRUE, and the other way around, of course.

When pause is over, we want the task thread to wake up,....

causing it to enter the catch block, if it was asleep :

The proper way to end the thread is, to let it finish its run method.

We set the reference to null, ....

so the loop will end and, with it, the run method.

When a thread has finished its run method, IT IS DEAD AND CANNOT BE STARTED AGAIN.

Your only option then is to make a new instance and start that, if you need it.

=======

NOTE

=======

A thread that's running is said to be RUNNABLE. A sleeping thread is NOT RUNNABLE.

Add to this a DEAD thread ( one that's finished its run method ) and NEW, one that hasn't been started yet, and you have the four possible THREAD STATES.

=======

This is important only if a thread could be pausing for a long time.

=======

When pausing, the thread runs this code every second.

=======

The thread should be able to sleep for much longer, but your browser's Java implementation may not handle the interruption correctly , so we'll stick with one second.

sleep is a static method, that explains the syntax.

So is currentThread.

.