Synchronization
In Java, two threads can communicate by accessing a shared variable (shared-memory model).
If two threads can both modify an object, that is, they can both execute a method that assigns to a shared variable, then the modifications must be synchronized.
This is easy - just declare the method to be synchronized! Java will associate a lock with each object containing the method - only one synchronized method from that object can be executed at a time.
Suppose more than one thread can access an account:
- public class Account
- { int bankBalance; ...
- public synchronized void CreditAcct(int amt)
- { ... bankBalance += amt; ... }}