Exercise 14.2: Modify the first version of PrintServer so that only the thread created in the constructor
can successfully execute run, using the identity of the thread as suggested.
14.3. Synchronization
Recall the bank teller example from the beginning of this chapter. When two tellers (threads) need to use the
same file (object), there is a possibility of interleaved operations that can corrupt the data. Such potentially
interfering actions are termed critical sections or critical regions, and you prevent interference by
synchronizing access to those critical regions. In the bank, tellers synchronize their actions by putting notes in
the files and agreeing to the protocol that a note in the file means that the file can't be used. The equivalent
action in multithreading is to acquire a lock on an object. Threads cooperate by agreeing to the protocol that
before certain actions can occur on an object, the lock of the object must be acquired. Acquiring the lock on
an object prevents any other thread from acquiring that lock until the holder of the lock releases it. If done
correctly, multiple threads won't simultaneously perform actions that could interfere with each other.
Every object has a lock associated with it, and that lock can be acquired and released through the use of
synchronized methods and statements. The term synchronized code describes any code that is inside a
synchronized method or statement.
14.3.1. synchronized Methods
A class whose objects must be protected from interference in a multithreaded environment usually has
appropriate methods declared synchronized( "appropriate" is defined later). If one thread invokes a
synchronized method on an object, the lock of that object is first acquired, the method body executed, and
then the lock released. Another thread invoking a synchronized method on that same object will block
until the lock is released:
Synchronization forces execution of the two threads to be mutually exclusive in time. Unsynchronized access
does not wait for any locks but proceeds regardless of locks that may be held on the object.