Java Reference
In-Depth Information
3.2.2
Explicitly Implementing the
Runnable
Interface
This is very similar to the technique described in the previous sub-section. With this
method, however, we fi rst create an application class that explicitly implements the
Runnable
interface. Then, in order to create a thread, we instantiate an object of our
Runnable
class and 'wrap' it in a
Thread
object. We do this by creating a
Thread
object and passing the
Runnable
object as an argument to the
Thread
constructor.
(Recall that the
Thread
class has seven constructors.) There are two
Thread
con-
structors that allow us to do this:
Thread (Runnable<object>)
Thread(Runnable<object>, String<name>)
(The second of these allows us also to name the thread.)
When either of these constructors is used, the
Thread
object uses the
run
method of
the
Runnable
object in place of its own (empty)
run
method.
Once a
Runnable
object has been used as an argument in the
Thread
constructor,
we may never again need to refer to it. If this is the case, we can create such an object
anonymously and dynamically by using the operator
new
in the argument supplied to
the
Thread
constructor, as shown in the example below. However, some people may
prefer to create a named
Runnable
object fi rst and then pass that to the
Thread
constructor, so the alternative code is also shown. The second method employs
about twice as much code as the fi rst, but might serve to make the process clearer.
Example (Same effect as that of
ThreadShowName
)
Note that, since the thread objects in this example are not of class
Thread
(since
RunnableShowName
does
not
extend
Thread
), they cannot make direct use of meth-
ods
getName
and
sleep
, but must go through class
Thread
to make use of static
methods
currentThread
and
sleep
. The former method is used to get a pointer to the
current thread, in order to use that pointer to call method
getName
.
public class RunnableShowName implements Runnable
{
public static void main(String[] args)
{
Thread thread1 =
new Thread(new RunnableShowName());
Thread thread2 =
new Thread(new RunnableShowName());
/*
As an alternative to the above 2 lines, the following
(more long-winded) code could have been used:
RunnableShowName runnable1 =
new RunnableShowName();
RunnableShowName runnable2 =
new RunnableShowName();
Thread thread1 = new Thread(runnable1);
Search WWH ::
Custom Search