package multithreading;
class Display
{
public void wish(String name)
{
for(int i=0;i<10;i++)
{
System.out.print("GoodMorning: ");
try
{
Thread.sleep(2000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
System.out.print(name);
System.out.println();
}
}
}
class MyThread5 extends Thread
{
String name;
Display d;
MyThread5(String name, Display d)
{
this.name = name;
this.d = d;
}
public void run()
{
d.wish(name);
}
}
public class SynchronizedDemo
{
public static void main(String[] args)
{
Display d = new Display();
MyThread5 mt1 = new MyThread5("Dhoni", d);
MyThread5 mt2 = new MyThread5("Yuvraj", d);
mt1.start();
mt2.start();
}
}
//Here on Same object of Display 'd' two threads are accessing wish()
//so we get irregular output
----------------------------
output (here we get irrigular output)
GoodMorning: GoodMorning: DhoniYuvraj
GoodMorning:
GoodMorning: DhoniYuvraj
GoodMorning:
GoodMorning: DhoniYuvraj
GoodMorning:
GoodMorning: YuvrajDhoni
GoodMorning:
GoodMorning: Dhoni
GoodMorning: Yuvraj
GoodMorning: Dhoni
GoodMorning: Yuvraj
GoodMorning: Dhoni
GoodMorning: Yuvraj
GoodMorning: Dhoni
GoodMorning: Yuvraj
GoodMorning: Dhoni
GoodMorning: Yuvraj
GoodMorning: Dhoni
Yuvraj
class Display
{
public void wish(String name)
{
for(int i=0;i<10;i++)
{
System.out.print("GoodMorning: ");
try
{
Thread.sleep(2000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
System.out.print(name);
System.out.println();
}
}
}
class MyThread5 extends Thread
{
String name;
Display d;
MyThread5(String name, Display d)
{
this.name = name;
this.d = d;
}
public void run()
{
d.wish(name);
}
}
public class SynchronizedDemo
{
public static void main(String[] args)
{
Display d = new Display();
MyThread5 mt1 = new MyThread5("Dhoni", d);
MyThread5 mt2 = new MyThread5("Yuvraj", d);
mt1.start();
mt2.start();
}
}
//Here on Same object of Display 'd' two threads are accessing wish()
//so we get irregular output
----------------------------
output (here we get irrigular output)
GoodMorning: GoodMorning: DhoniYuvraj
GoodMorning:
GoodMorning: DhoniYuvraj
GoodMorning:
GoodMorning: DhoniYuvraj
GoodMorning:
GoodMorning: YuvrajDhoni
GoodMorning:
GoodMorning: Dhoni
GoodMorning: Yuvraj
GoodMorning: Dhoni
GoodMorning: Yuvraj
GoodMorning: Dhoni
GoodMorning: Yuvraj
GoodMorning: Dhoni
GoodMorning: Yuvraj
GoodMorning: Dhoni
GoodMorning: Yuvraj
GoodMorning: Dhoni
Yuvraj
No comments:
Post a Comment