Synchronized blocks in Java are used to synchronize a block of code. There are some cases where we need synchronize only a part of code in that cases we use synchronized blocks. The syntax for the synchronized block is given below.
//write code here
Some times when we don't have access to a class and still we need synchronization between objects then use synchronized blocks. It might be little confusing now. Look at the example program so that can understand easily.
public static void main(String args)
FathersAccount fatherAccount = new FathersAccount(); // LINE A
Children thread1 = new Children(fatherAccount, 1000); // LINE B
Children thread2 = new Children(fatherAccount, 2000);
Children thread3 = new Children(fatherAccount, 3000);
void deposit(double amount)
System.out.println(Thread.currentThread().getName() + " deposited " + amount + "in FathersAccount.");
currentBalance += amount;
catch (Exception e)
System.out.println("Current Balance in FathersAccount " + currentBalance);
class Children extends Thread
Children(FathersAccount fatherAccount, double amount)
this.fatherAccount = fatherAccount;
this.amount = amount;
public void run()
synchronized (fatherAccount) // LINE C
fatherAccount.deposit(amount); // LINE D
Thread-1 deposited 2000.0in FathersAccount.
Current Balance in FathersAccount 2000.0
Thread-2 deposited 3000.0in FathersAccount.
Current Balance in FathersAccount 5000.0
Thread-0 deposited 1000.0in FathersAccount.
Current Balance in FathersAccount 6000.0
In the above program we have three classes
LINE A we have created an object for
LINE B we have created three threads for
Children and running them by invoking thread's
run method which in turn invokes
run method. At
LINE C inside
run method we have synchroninzed
fatherAccount so that no two children access the
fatherAccount at same time. At
LINE D we are invoking
deposit method since we have synchronized
fatherAccount the thread's access the method one after other.
THINGS TO TRY
- Remove the synchronized block at
LINE C and see the output.