A block of code may be explicitly labeled as synchronized with this Java syntax:
synchronized( someObject ) {
. . .
/* Code executed within the monitor of someObject */
. . .
}
As a convenience, a class in Java can also declare some of its methods to be synchronized. Such a declaration
is the same as synchronizing on this particular instance of the class. Thus, when one thread is executing any one
of the synchronized methods of the class, no other thread will be allowed to execute any synchronized method
of that instance of the class, whether the same synchronized method or a different one.
Java monitors differ from the classical monitor idea in that Java monitors do not support condition variables.
However, a thread can decide to wait while in the monitor, and give up the lock on the monitor while waiting,
by using the synchronizing object??™s wait() method. Likewise, a thread waiting in the monitor can be awakened
when another thread in the monitor uses the object??™s notify() method.
Here is an example of a class that could be used to implement a producer??“consumer relationship between
threads in Java. As long as the producer and consumer reference the same instance of the class PC, their interaction
will occur correctly because the putMessage and getMessage methods are synchronized:
import java.
Pages:
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298