Drop Down

Monday, January 6, 2020

Synchronized Demo_2

package multithreading;

class Display
{
//public void wish(String name)
public synchronized 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 we are making wish method as synchronized so at a time only one thread can access wish method, this is to handle Race Condition.

---------------------------------------------------------------------------------------
output:
---------

GoodMorning: Dhoni
GoodMorning: Dhoni
GoodMorning: Dhoni
GoodMorning: Dhoni
GoodMorning: Dhoni
GoodMorning: Dhoni
GoodMorning: Dhoni
GoodMorning: Dhoni
GoodMorning: Dhoni
GoodMorning: Dhoni
GoodMorning: Yuvraj
GoodMorning: Yuvraj
GoodMorning: Yuvraj
GoodMorning: Yuvraj
GoodMorning: Yuvraj
GoodMorning: Yuvraj
GoodMorning: Yuvraj
GoodMorning: Yuvraj
GoodMorning: Yuvraj
GoodMorning: Yuvraj

No comments:

Post a Comment

Java 8 Notes Pics