The manipulation of a single thread is done with four operations:
There are essentially two ways of making a thread. See also the examples below.
Thread
that may be subclassed.Runnable
. This is
good practice if the class is
already a subclass of another class. To activate such an object as a
thread, you start an new instance of the thread class
with this object as an argument, like in mythread = new Thread(myobject)
.start()
. This means
that at this moment, the thread will get its first turn from
the Virtual Machine and the run()
method of the
thread is called.
run()
method is the heart of the thread (or the runnable object).
This method is called automatically by the start-method, it is not directly called by
the user. It contains the sequence of instructions that
belongs to this thread. If this method exits, the thread stops.
So for continuous movements like in the above applet,
you will find a never ending loop. At some moment, you may tell
the thread to sleep, e.g. with Thread.sleep(30)
the
thread will go asleep for 30 miliseconds.
The thread stops when the run-method exits, or when an explicit
stop()
call is done.
CAVEAT: When making an applet, it is important to
stop your threads. Otherwise, the threads keep running
as long as the browser is up, even when the page containing the applet is not visible.
You stop your threads in the following way: implement the stop()
method
of the applet and include calls to the stop-methods of all threads.
In this example we make a class Ball that extends the Thread class. The code shows how the run-method is implemented. Note that the sleep-method might generate an exception, so it has to be surrounded by a try-catch construct. The buttons do a call to the creation, the start and the stop method. The code for the Ball is in the file Ball.java, the code for the interface is in the file SingleThreadApplet.java
class Ball extends Thread { ... public void run ( ) { while (true) { move(); applet.repaint(); try { Thread.sleep(time); } catch (InterruptedException e) { break; } } } void move ( ) { ... } }
In contrast with the previous example, the current class is not a subclass of the thread class,
but it implements the Runnable interface. This means that it contains a method
run()
,
and therefore can be used as an argument for a thread object. In this case this thread object is
an instance variable of the class itself, and we encounter therefore the instantiation
thread = new Thread(this)
Note that we implement methods to pass on the start
and the stop. The code for the class is in the file
RunnableBall.java, the code for the
applet is in RunnableBallApplet.java
class RunnableBall implements Runnable { Thread thread; ... RunnableBall (...) { ... thread = new Thread(this); } public void start () { thread.start(); } public void stop () { thread.stop(); } public void run ( ) { while (true) { move(); applet.repaint(); try { Thread.sleep(30); } catch (InterruptedException e) { break; } } } void move () { ...} }