Block synchronization :
- Synchronized block is used to lock an object for any shared resource.
- Scope of synchronized block is smaller than the method.
- Generally we synchronize methods as shown in the above discussion.
- Block synchronization is used to synchronize a set of lines of code in a method.
- If you put all the codes of the method in the synchronized block, it will work same as the synchronized method.
class PrintNumers
{
void print(int n)
{
for(int i=1 ; i<=5 ; i++)
{
System.out.println("Parallel : "+i);
try
{
Thread.sleep(500);
}
catch (Exception e){ }
}
synchronized(this)
{
for(int i=1;i<=5;i++)
{
System.out.println("Sequential of "+n+" multiples : "+n*i);
try
{
Thread.sleep(400);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
}
class MyThread1 extends Thread
{
PrintNumers pn;
MyThread1(PrintNumers pn)
{
this.pn = pn;
}
public void run()
{
this.pn.print(5);
}
}
class MyThread2 extends Thread
{
PrintNumers pn;
MyThread2(PrintNumers pn)
{
this.pn = pn;
}
public void run()
{
this.pn.print(100);
}
}
class SynchronizedBlock
{
public static void main(String args[])
{
PrintNumers obj = new PrintNumers();
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}