Wednesday, February 25, 2009

Example code thread synchronization



package thread;
class Display
{
public synchronized void show(String name)
{
for(int i=0;i<2;i++)
{
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 ThreadDemo2
{
public static void main(String a[])throws Exception
{
Display d=new Display();
MyThread1 t1=new MyThread1(d,"java");
MyThread1 t2=new MyThread1(d,"Sun");
t1.start();
t2.start();

}
}

output:
Good Morning:
java
Good Morning:
java
Good Morning:
Sun
Good Morning:
Sun



0 comments:

Post a Comment