Java Reference
In-Depth Information
Yo u create a thread class in one of two ways:
1. Create a subclass of the
Thread
class and override the
run()
method.
2. Create a class that implements the
Runnable
interface, which has only one method:
run()
.Pass a reference to this class in the constructor of
Thread
. The thread then
calls back to this run
()
method when the thread starts.
In the following sections we examine these two thread creation techniques
further.
8.2.1 Thread creation: subclass
Creating a subclass of
Thread
offers the most conceptually straightforward
approach to threading. In this approach the subclass overrides the
run()
method
with the code you wish to process. The following code segments illustrate this
approach.
The class
MyThread
extends the
Thread
class and overrides the method
run()
with one that contains a loop that prints out a message until a counter
hits 20.
public class
MyThread
extends Thread
{
public void run ()
{
int count
=
0;
while (true)
{
System.out.println ("Thread alive");
// Print every 0.10sec for 2 seconds
try {
Thread.sleep (100);
}
catch (InterruptedException e) {}
count++;
if (count >= 20) break;
}
System.out.println ("Thread stopping");
} // run
} // class MyThread
In
MyApplet
shown below, the
start()
method creates an instance of the
MyThread
class and invokes the thread's
start()
method. This will in turn
invoke the
run()
method. The thread goes into a loop and prints a message every
100 ms using the
Thread
class static method
sleep(long time)
,where time
Search WWH ::
Custom Search