Wednesday, March 4, 2009

example synchronized static method



package mythread;
/*If you want to execute any static synchronized method, first the thread should required a class level lock.
If a thread has class level lock, it is allowed to execute any stock synchronized method. During that time no other thread is allowed to execute any static synchronized method. But the remaining threads are allowed to execute any static non synchronized methods of the same class.*/

class Display
{
public synchronized static void show(String name)
{

System.out.println("Good Morning:");
try
{
Thread.sleep(2000);
}
catch(InterruptedException e){}
System.out.println(name);

}
}
class MyThread1 extends Thread
{
Display d;
String name;
MyThread1(Display d, String name)
{
this.d=d;
this.name=name;
}
public void run()
{
d.show(name);
}

}
public class Staticsync
{
public static void main(String a[])throws Exception
{
Display d=new Display();
MyThread1 t1=new MyThread1(d,"java");
MyThread1 t2=new MyThread1(d,"static method");
t1.start();
t2.start();

}
}

output :
Good Morning:
java
Good Morning:
static method




0 comments:

Post a Comment