Method level synchronization prevents two threads from executing method on an object at the same time. A method can be synchronized by using the synchronized keyword as a modifier in the method declaration. Its syntax is a follows,
[accessspecifier] synchronized returnType methodName (paramaterList) {
// body of the method
}
When a thread invokes a synchronized method on an object, the thread first acquires a lock on that object, executes the body of the method and then releases the lock. Once a lock has been obtained by one thread, no other thread can acquire the lock on the object until the thread releases the lock. This means another thread invoking the synchronized method on that same object will have to wait until the lock has been released. If several threads attempt to execute a method on a locked object at the same time, a queue of suspended threads will be formed. When the thread that acquired the lock releases it, only one of the queue thread will access the object.
class Account { private double balance = 5000; public double getBalance() { return balance ; } public synchronized void deposit(double amount ) { System.out.println(Thread.currentThread().getName() + " Read Balance : " + balance); double newBalance = balance + amount; try { Thread.sleep(1000); } catch(InterruptedException ex){} balance = newBalance; } } class AddAmountTask implements Runnable { Account acct; AddAmountTask(Account ac) { acct = ac; } public void run() { acct.deposit(100); } } class SynchronizedEx { public static void main(String[] args) { Account a = new Account(); //shared resource AddAmountTask t = new AddAmountTask(a); Thread t1= new Thread(t); Thread t2 = new Thread(t); Thread t3 = new Thread(t); t1.start(); t2.start();t3.start(); try { t1.join(); t2.join(); t3.join(); } catch(InterruptedException ex){} System.out.println("Total Balance in Account is : " + a.getBalance()); } }