1 |
In Java, two threads can communicate by accessing a shared variable (shared-memory model).
|
2 |
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.
|
3 |
This is easy - just declare the method to be synchronized!
|
4 |
This means that Java will ensure that only one thread executes the method at a time and is not interrupted.
|
5 |
Suppose more than one thread has an instance of an account:
-
public class Account
-
{ int bankBalance; ...
-
public synchronized void CreditAcct(int amt)
-
{ ... bankBalance += amt; ... }}
|