Java Reference
In-Depth Information
3.2
Using Threads in Java
Java is unique amongst popular programming languages in making multithreading
directly accessible to the programmer, without him/her having to go through an
operating system API. Unfortunately, writing multithreaded programs can be rather
tricky and there are certain pitfalls that need to be avoided. These pitfalls are caused
principally by the need to coordinate the activities of the various threads, as will be
seen in Sect. 3.4 .
In Java, an object can be run as a thread if it implements the inbuilt interface Runnable ,
which has just one method: run . Thus, in order to implement the interface, we simply
have to provide a defi nition for method run . Since the inbuilt class Thread implements
this interface, there are two fundamental methods for creating a thread class:
￿ create a class that extends Thread ;
￿ create a class that does not extend Thread and specify explicitly that it imple-
ments Runnable .
Of course, if the application class already has a superclass (other than Object ),
extending Thread is not an option, since Java does not support multiple inheritance.
The following two sub-sections consider each of the above methods in turn.
3.2.1
Extending the Thread Class
The run method specifi es the actions that a thread is to execute and serves the
same purpose for the process running on the thread as method main does for a full
application program. Like main , run may not be called directly. The containing
program calls the start method (inherited from class Thread ), which then auto-
matically calls run .
Class Thread has seven constructors, the two most common of which are:
￿
Thread()
￿
Thread(String<name>)
The second of these provides a name for the thread via its argument. If the fi rst
is used, the system generates a name of the form Thread-n, where n is an integer
starting at zero and increasing in value for further threads. Thus, if three threads are
created via the fi rst constructor, they will have names Thread-0 , Thread-1 and
Thread-2 respectively. Whichever constructor is used, method getName may be
used to retrieve the name.
Example
Thread fi rstThread = new Thread();
Thread secondThread = new Thread("namedThread");
System.out.println(fi rstThread.getName());
System.out.println(secondThread.getName());
Search WWH ::




Custom Search