Java Reference
In-Depth Information
Therefore, in the real world you typically create a thread by writing a class that
implements Runnable and associating it as a target of a new Thread object. That being
said, we will discuss in detail both ways to write a thread in Java because the exam
objectives specifi cally state knowledge of both techniques.
Implementing the Runnable Interface
You can write a thread in Java by writing a new class that implements the Runnable
interface and assigning an instance of the class to a new Thread object. A Runnable target is
associated with a new Thread object using one of the following constructors in the Thread
class:
public Thread(Runnable target)
public Thread(Runnable target, String name)
public Thread(ThreadGroup group, Runnable target)
public Thread(ThreadGroup group, Runnable target, String name)
public Thread(ThreadGroup group, Runnable target, String name, long
stackSize)
You can assign a Thread object a name so that your application can monitor its threads.
You can also specify a stack size that, according to the Java API documentation, is highly
platform dependent. The stack size is the approximate number of bytes of address space
that the virtual machine is to allocate for this thread's stack.
Using the Thread constructors that declare a ThreadGroup parameter, you
can assign your Thread object to a ThreadGroup . A ThreadGroup allows
you to organize and manage the threads of your application into groups.
The SCJP exam does not require knowledge of the ThreadGroup class.
Let's look at an example of creating a new thread by writing a class that implements the
Runnable interface. The following SayHello class implements the Runnable interface and
has one fi eld, one constructor, and the necessary run method:
1. public class SayHello implements Runnable {
2. private String greeting;
3.
4. public SayHello(String greeting) {
Search WWH ::




Custom Search