When you have to share data between multiple threads, you have to protect access to that piece of data using a synchronization mechanism. You can use the synchronized keyword in the declaration of the method that modifies the data so that only one thread can modify data at a time. Another possibility is the utilization of a Lock class to create a critical section with instructions that modify data.
Since version 5, Java includes atomic variables. When a thread is doing an operation with an atomic variable, the implementation of the class includes a mechanism to check that the operation is done in one step. Basically, the operation gets the value of the variable, changes the value in a local ...