Overview

Chapter 3 - Creating and Starting a Thread

Java Thread Programming
Paul Hyde
  Copyright 1999 Sams Publishing

Thread Constructors
The central constructor in Thread is
public Thread(ThreadGroup group , Runnable target, String name )
The parameter name allows you to specify the name of the thread at construction time, rather than set it later using setName() .
The parameter target refers to an object of type Runnable . This objects run() method will be invoked by the new thread instead of the run() method of Thread . Unlike a threads name, if youre going to specify the target , you must do so at the time of construction. Chapter 4 explores in detail the issues involved in making a decision to use Runnable instead of extending Thread .
The parameter group lets you specify the ThreadGroup to which the new Thread will belong. Figure 3.1 shows the relationships among Thread s and ThreadGroup s.
Figure 3.1: A sample hierarchy of ThreadGroups and Threads.
An analogy can be drawn between the file system concept of directories and files and the ThreadGroup / Thread relationship. In a file system, a directory can contain files and other directories. These other directories, in turn , can contain other files and directories. Every file is in exactly one directory, which may itself be in another directory. Every directory except the one root or base directory is in another directory.
In Java, a ThreadGroup (much like a directory) can contain Thread s and other ThreadGroup s. These other ThreadGroup s can, in turn, contain other Thread s and ThreadGroup s. Every Thread (much like a file) is a member of a ThreadGroup , which may itself be a member of another ThreadGroup .
If a ThreadGroup is not specified at the time of a Thread s construction, the ThreadGroup is inherited from the Thread that constructed it. Chapter 10, Thread Groups, discusses ThreadGroup s in more detail.
The Thread constructor used so far has been as follows :
public Thread()
By default, the ThreadGroup is that of the Thread that constructs it. No external Runnable is specified, so the Thread s own run() method is called. Because no name is specified, the name of the Thread will be automatically generated as something such as Thread-0 .
The other constructors of Thread come somewhere in between the zero-argument constructor and the three-argument constructor. They specify some parameters of the three-argument constructor, and the nonspecified parameters take on their default values.

Toc


Java Thread Programming
Java Thread Programming
ISBN: 0672315858
EAN: 2147483647
Year: 2005
Pages: 149
Authors: Paul Hyde

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net