O'Reilly logo

Java, A Beginner’s Guide, 5th Edition by Herbert Schildt

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required