Thursday, January 16, 2014

Static Synchronization Example

If we make any static method as synchronized, the lock will be on class not on object.


//example of static synchronization

class statSync
{
synchronized static void printTable(int n)
{
for( int i=0;i<5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(500);
}
catch(Exception e){}
}
}
}
class MyThread5 extends Thread
{
public void run()
{
statSync.printTable(1);
}
}
class MyThread6 extends Thread
{
public void run()
{
statSync.printTable(10);
}
}
class MyThread7 extends Thread
{
public void run()
{
statSync.printTable(100);
}
}
class MyThread8 extends Thread
{
public void run()
{
statSync.printTable(1000);
}
}
class Use3
{
public static void main(String surat[])
{
MyThread5 t5=new MyThread5();
MyThread6 t6=new MyThread6();
MyThread7 t7=new MyThread7();
MyThread8 t8=new MyThread8();
t5.start();
t6.start();
t7.start();
t8.start();
}
}

Output:

No comments:

Post a Comment