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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access