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 the object. While locked, no other thread can enter the method, or enter any other synchronized method defined by the object’s class. When the thread returns from the method, the monitor unlocks the object, allowing it to be used by the next thread. Thus, synchronization is achieved with virtually no programming effort on your part.
The following program demonstrates synchronization by controlling access to a method called sumArray( ), which sums the elements of an integer array.
The output from the program is shown here. (The precise output ...
Get Java, A Beginner's Guide, 5th Edition, 5th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.