❮ Previous Next ❯

Java Block Synchronization

Sometimes we synchronize some specific portion of code, then we use block synchronization.

That means synchronizing specific code is known as block synchronization.

Example

class Demo
{
void print(int n)
{
synchronized(this) // synchronized block
{
for(int i=1;i<=3;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(500);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
}
class MyThread1 extends Thread
{
Demo d;
MyThread1(Demo d)
{
this.d=d;
}
public void run()
{
d.print(5);
}
}
class MyThread2 extends Thread
{
Demo d;
MyThread2(Demo d)
{
this.d=d;
}
public void run()
{
d.print(10);
}
}
public class SynchronizationExa2
{
public static void main(String args[])
{
Demo obj = new Demo();
MyThread1 obj1=new MyThread1(obj);
MyThread2 obj2=new MyThread2(obj);
obj1.start();
obj2.start();
}
}
Output

5
10
15
10
20
30

❮ Previous Next ❯



  Tutorials

Popular Links

Contact Us

address Plot No-741,2ND Floor
Opp. Bhagabati Temple,Jayadev Vihar
      Bhubaneswar-751013
      Email: info@silantechnology.com
      Phone: 0674-2361252
address
39877, sundale dr, apt#101, Fremont, California 94538, USA
       Phone: +1(262)388-7619

facebook twitter google linked in

© 2018 Silan Technology. All Rights Reserved