Synchronization example using wait () / notify () :
public class Main { public static void main(String[] args) { Account account = new Account(); new Thread(new Wife(account)).start(); new Thread(new Husband(account)).start(); } } public class Account { private int account; public boolean turn; public synchronized int deposit() { turn = !turn; account += 300; return account; } } public abstract class FamilyMember implements Runnable { private final String name; protected final Account account; public FamilyMember(String name, Account account) { this.name = name; this.account = account; } public abstract boolean isMyTurn(); public void run() { for (int i = 0; i < 10; i++) { synchronized (account) { while (!isMyTurn()) { try { account.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(name + " " + i + " " + account.deposit()); account.notify(); } } } } public class Wife extends FamilyMember { public Wife(Account account) { super("Wife", account); } @Override public boolean isMyTurn() { return !account.turn; } } public class Husband extends FamilyMember { public Husband(Account account) { super("Husband", account); } @Override public boolean isMyTurn() { return account.turn; } }
The invoice holds the turn flag, which determines which turn it is to deposit money. The shared code has moved to the FamilyMember class, the husband and wife wait in line using the isMyTurn() method.
Of course, it was clumsy, but it gives an idea of using wait() and notify() .
This solution is similar to the solution of Suvitruf , but instead of Thread.sleep() , wait() used to wait() until the condition is met, which is more efficient because the program sleeps better. The notify() method notifies you of a condition change and wakes up the waiting thread.
wait() must be used in a loop, because the thread can wake up without calling notify() .
Instead of the flag account.turn , you can probably use the value of the account. If the amount on the account has changed, then the turn to put the money goes to another. To do this, you will need to add a synchronized method Account.get() , which will return the current amount in the account. The husband / wife memorizes the amount in the account after they have deposited the money and waits for the amount to change.
wifeandhusbandmethodsrunenough to writeAccount.deposit()and inmainwrite afor (int i = 0; i < 10; i++) { wife.start.... husband.start.....husband.join() }loopfor (int i = 0; i < 10; i++) { wife.start.... husband.start.....husband.join() }......... here's an example ideone.com/Fqe5g8 - Alexey Shimansky