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.
Syntax:
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.
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
}
}
}
OUTPUTThread-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
DESCRIPTIONIn 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.