Java Reference
In-Depth Information
Q :
Does the operating system's implementation of multitasking affect how much
CPU time a thread receives?
A : Aside from a thread's priority setting, the most important factor affecting thread exe-
cution is the way the operating system implements multitasking and scheduling.
Some operating systems use preemptive multitasking in which each thread receives a
time slice, at least occasionally. Other systems use nonpreemptive scheduling in
which one thread must yield execution before another thread will execute. In non-
preemptive systems, it is easy for one thread to dominate, preventing others from
running.
Synchronization
When using multiple threads, it is sometimes necessary to coordinate the activities of two
or more. The process by which this is achieved is called synchronization . The most com-
mon reason for synchronization is when two or more threads need access to a shared re-
source that can be used by only one thread at a time. For example, when one thread is writ-
ing to a file, a second thread must be prevented from doing so at the same time. Another
reason for synchronization is when one thread is waiting for an event that is caused by an-
other thread. In this case, there must be some means by which the first thread is held in a
suspended state until the event has occurred. Then, the waiting thread must resume execu-
tion.
Key to synchronization in Java is the concept of the monitor , which controls access to an
object. A monitor works by implementing the concept of a lock . When an object is locked
by one thread, no other thread can gain access to the object. When the thread exits, the ob-
ject is unlocked and is available for use by another thread.
All objects in Java have a monitor. This feature is built into the Java language, itself.
Thus, all objects can be synchronized. Synchronization is supported by the keyword syn-
chronized and a few well-defined methods that all objects have. Since synchronization was
designed into Java from the start, it is much easier to use than you might first expect. In
fact, for many programs, the synchronization of objects is almost transparent.
There are two ways that you can synchronize your code. Both involve the use of the syn-
chronized keyword, and both are examined here.
Using Synchronized Methods
You can synchronize access to a method by modifying it with the synchronized keyword.
When that method is called, the calling thread enters the object's monitor, which then locks
Search WWH ::




Custom Search