Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
The following example shows what can happen when two threads (Ryan and Monica) share a single object (the bank account).
The code has two classes, BankAccount, and MonicaAndRyanJob. The MonicaAndRyanJob class implements Runnable, and represents the behavior that Ryan and Monica both have—checking the balance and making withdrawals. But of course, each thread falls asleep in between checking the balance and actually making the withdrawal.
The MonicaAndRyanJob class has an instance variable of type BankAccount., that represents their shared account.
The code works like this:
Make one instance of RyanAndMonicaJob.
The RyanAndMonicaJob class is the Runnable (the job to do), and since both Monica and Ryan do the same thing (check balance and withdraw money), we need only one instance.