package multithreading;
import java.util.concurrent.locks.ReentrantLock;
class Displays
{
ReentrantLock l = new ReentrantLock();
public void wish(String name)
{
l.lock();
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();
}
l.unlock();
}
}
class MyThread6 extends Thread
{
String name;
Displays d;
MyThread6(String name, Displays d)
{
this.name = name;
this.d = d;
}
public void run()
{
d.wish(name);
}
}
public class Synchronized_Using_ReentrantLock
{
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();
}
}
----------------------------------------------------------
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
import java.util.concurrent.locks.ReentrantLock;
class Displays
{
ReentrantLock l = new ReentrantLock();
public void wish(String name)
{
l.lock();
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();
}
l.unlock();
}
}
class MyThread6 extends Thread
{
String name;
Displays d;
MyThread6(String name, Displays d)
{
this.name = name;
this.d = d;
}
public void run()
{
d.wish(name);
}
}
public class Synchronized_Using_ReentrantLock
{
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();
}
}
----------------------------------------------------------
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