Topics Index

Multithreaded Programming > Synchronization >
Siva Nookala - 20 Feb 2017
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.
synchronized (object)
    //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.
class Banking
    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);

class FathersAccount
    double currentBalance;

    void deposit(double amount)
        System.out.println(Thread.currentThread().getName() + " deposited " + amount + "in FathersAccount.");
        currentBalance += amount;
        catch (Exception e)
            System.out.println("Thread Interrupted");
        System.out.println("Current Balance in FathersAccount " + currentBalance);

class Children extends Thread
    FathersAccount fatherAccount;
    double amount;

    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 Banking, FathersAccount and Children. At LINE A we have created an object for FathersAccount. At LINE B we have created three threads for Children and running them by invoking thread's run method which in turn invokes Children 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 FathersAccount deposit method since we have synchronized fatherAccount the thread's access the method one after other.

  • Remove the synchronized block at LINE C and see the output.

Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.