Java Reference
In-Depth Information
The Thread class has eight constructors, which take in a variation of the fol-
lowing parameters:
String name. Every Thread object has a name associated with it. You can
assign a thread any name you like because the purpose of the name is to
allow you to distinguish the various threads you create. If you do not
assign your threads a name, the Thread class names them Thread0,
Thread1, Thread2, and so on.
Runnable target. Associates a Runnable object as the target of the
Thread. If you write a separate class that implements Runnable, use one
of the Thread constructors that has a Runnable parameter.
ThreadGroup. The group that the thread belongs to. All threads belong
to a group. If you create your own ThreadGroup object, use one of the
Thread constructors that has a ThreadGroup parameter to associate the
new thread with your group. If you do not explicitly put a thread into a
group, the thread is placed in the default thread group.
long stackSize. The number of bytes you want allocated for the size of
the stack used by this thread. The documentation warns that this value
is highly platform dependent and may be ignored on some JVMs.
Every thread belongs to a thread group . The java.lang.ThreadGroup class
represents a thread group, and Thread objects are associated with a group
using one of the Thread constructors with a ThreadGroup parameter. If a
thread is not specifically added to a thread group, it belongs to the
default thread group created by the JVM called main. Creating a
ThreadGroup is useful when managing a large number of threads.
After you instantiate the Thread object and associate it with the Runnable
target, this new thread is started by invoking the start() method of the Thread
object. The following RunnableDemo program demonstrates instantiating
both a Runnable object (the DisplayMessage object) and a corresponding
Thread object. Then, the start() method is invoked on the Thread object, which
causes the run() method of DisplayMessage to execute in a separate thread.
Study the program and see if you can determine what the output is.
public class RunnableDemo
{
public static void main(String [] args)
{
System.out.println(“Creating the hello thread...”);
DisplayMessage hello = new DisplayMessage(“Hello”);
Thread thread1 = new Thread(hello);
Search WWH ::




Custom Search