Java Reference
In-Depth Information
Figure 6-4. hread lifecycle
Threads can also be made to sleep, by using the Thread.sleep() method. This takes
an argument in milliseconds, which indicates how long the thread would like to
sleep for, like this:
try {
Thread . sleep ( 2000 );
} catch ( InterruptedException e ) {
e . printStackTrace ();
The argument to sleep is a request to the operating system,
not a demand. For example, it is possible to sleep for longer
than requested, depending on load and other factors specific
to the runtime environment.
We will discuss the other methods of Thread later in this chapter, but first we need
to cover some important theory that deals with how threads access memory, and
that is fundamental to understanding why multithreaded programming is hard and
can cause developers a lot of problems.
Visibility and Mutability
In Java, this essentially equates to all Java application threads in a process having
their own stacks (and local variables) but sharing a single heap. This makes it very
easy to share objects between threads, as all that is required is to pass a reference
from one thread to another. This is illustrated in Figure 6-5 .
Search WWH ::

Custom Search