The basic synchronization primitives provided in Java are very easy to use, and well-suited to the majority of situations a programmer sees. In many respects they are simpler, easier to use, and less prone to errors than their counterparts in POSIX threads (Pthreads). They do not, however, cover all situations and extending them is not always obvious.
PROVIDING PROTECTION
The first thing that synchronization techniques must provide is a method to ensure that updates to shared data are done in a correct fashion. In particular, many updates comprise several distinct operations and those operations must be done together, atomically. The canonical example is a program that updates your bank account. In Listing 1, it should be obvious that thread number 1 could overwrite the data that thread number 2 had just saved.
The solution to this is to ensure that each of those operations happen atomically. In Java, this is done with a synchronized method (objects with such synchronization are known as monitors). Now the second method will have to wait for the one called first to complete before it can start. The code in Listing 2 will operate correctly.
Pthreads accomplishes the same behavior by using explicit mutex locks. While functionally equivalent, using explicit mutexes suffers from the added complexity of the programmer having to remember which locks to use and to unlock them after use. This is not a big problem, but when writing complex code that has numerous branches and return statements, mistakes do happen (I speak from experience!) and it can be irritating to track down.