Java Reference
In-Depth Information
Current thread's name: main
Current thread's group name: main
New thread's name: my new thread
New thread's group name: main
You can also create a thread group and place a new thread in that thread group. To place a new thread in your
thread group, you must use one of the constructors of the
Thread
class that accepts a
ThreadGroup
object as an
argument. The following snippet of code places a new thread in a particular thread group:
// Create a new ThreadGroup
ThreadGroup myGroup = new ThreadGroup("My Thread Group");
// Make the new thread a member of the myGroup thread group
Thread t = new Thread(myGroup, "myThreadName");
Thread groups are arranged in a tree-like structure. A thread group can contain another thread group. The
getParent()
method of the
ThreadGroup
class returns the parent thread group of a thread group. The parent of
the top-level thread group is
null
.
The
activeCount()
method of the
ThreadGroup
class returns an estimate of the number of active threads in the
group. The
enumerate()
method of the
ThreadGroup
class can be used to get the threads in a thread group.
A thread group in a Java program can be used to implement a group-based policy that applies to all threads in a
thread group. For example, by calling the
interrupt()
method of a thread group, you can interrupt all threads in the
thread group.
Volatile Variables
I have discussed the use of the
synchronized
keyword in previous sections. Two things happen when a thread
executes a
synchronized
method/block.
•
The thread must obtain the monitor lock of the object on which the method/block is
synchronized.
•
The thread's working copy of the shared variables is updated with the values of those variables
in the main memory just after the thread gets the lock. The values of the shared variables in
the main memory are updated with thread's working copy value just before the thread releases
the lock. That is, at the start and at the end of a
synchronized
method/block, the values of the
shared variables in thread's working memory and the main memory are synchronized.
What can you do to achieve only the second point without using a
synchronized
method/block? That is, how
can you keep the values of variables in a thread's working memory in sync with their values in the main memory?
The answer is the keyword
volatile
. You can declare a variable
volatile
like so:
volatile boolean flag = true;
For every read request for a
volatile
variable, a thread reads the value from the main memory. For every write
request for a
volatile
variable, a thread writes the value to the main memory. In other words, a thread does not
cache the value of a
volatile
variable in its working memory. Note that using a
volatile
variable is useful only
in a multi-threaded environment for variables that are shared among threads. It is faster and cheaper than using a
synchronized
block.