Program:-
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
class Display
{
ReentrantLock l=new ReentrantLock();
public void wish(String name)
{
l.lock();
for(int i=1;i<=5;i++){
System.out.print("Good morning: ");
try{Thread.sleep(500);}catch(Exception e){}
System.out.println(name);
}
l.unlock();
}
}
class ThreadDemo2 extends Thread
{
Display d;
String name;
ThreadDemo2(Display d, String name)
{
this.d=d;
this.name=name;
}
public void run()
{
d.wish(name);
}
public static void main(String args[])
{
Display d=new Display();
ThreadDemo2 f1=new ThreadDemo2(d,"dhoni");
ThreadDemo2 f2=new ThreadDemo2(d,"shiva");
f1.start();
f2.start();
}
}
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
class ThreadDemo3 extends Thread
{
ThreadDemo3(String name)
{
super(name);
}
static ReentrantLock l=new ReentrantLock();
public void run()
{
if(l.tryLock())
{
System.out.println(Thread.currentThread().getName()+" Get the lock");
try{Thread.sleep(500);}catch(Exception e){}
l.unlock();
}
else
System.out.println(Thread.currentThread().getName()+" won't get the lock");
}
public static void main(String args[])
{
ThreadDemo3 t1=new ThreadDemo3("Thread1");
ThreadDemo3 t2=new ThreadDemo3("Thread2");
t1.start();
t2.start();
}
}
Comments
Post a Comment