Topics Index

SynchronizedBlocks - Java Example Program

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.

© meritcampus 2019

All Rights Reserved.

Open In App