Menu
Topics Index
...
`

SynchronizedBlocks - Java Example Program


SynchronizedBlocks
class Banking
{
    public static void main(String[] args)
    {
        FathersAccount fatherAccount = new FathersAccount(); // LINE A
        Children thread1 = new Children(fatherAccount, 1000); // LINE B
        thread1.start();
        Children thread2 = new Children(fatherAccount, 2000);
        thread2.start();
        Children thread3 = new Children(fatherAccount, 3000);
        thread3.start();
    }
}

class FathersAccount
{
    double currentBalance;

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

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
        }
    }
}
OUTPUT

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

DESCRIPTION

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.

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

© meritcampus 2019

All Rights Reserved.

Open In App