package multithreading;
import java.util.concurrent.locks.ReentrantLock;
class MyyThread extends Thread
{
static ReentrantLock l = new ReentrantLock();
MyyThread(String name)
{
super(name);
}
@Override
public void run()
{
if(l.tryLock())
{
System.out.println(Thread.currentThread().getName() + " ..got lock and performing safe operation.");
try
{
Thread.sleep(2000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
l.unlock();
}
else
{
System.out.println(Thread.currentThread().getName() + " ..unable to get lock and performing alternative operation.");
}
}
}
public class ReentrantLock_Demo3
{
public static void main(String[] args)
{
MyyThread mt = new MyyThread("F1 Thread");
MyyThread mt2 = new MyyThread("F2 Thread");
mt.start();
mt2.start();
}
}
import java.util.concurrent.locks.ReentrantLock;
class MyyThread extends Thread
{
static ReentrantLock l = new ReentrantLock();
MyyThread(String name)
{
super(name);
}
@Override
public void run()
{
if(l.tryLock())
{
System.out.println(Thread.currentThread().getName() + " ..got lock and performing safe operation.");
try
{
Thread.sleep(2000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
l.unlock();
}
else
{
System.out.println(Thread.currentThread().getName() + " ..unable to get lock and performing alternative operation.");
}
}
}
public class ReentrantLock_Demo3
{
public static void main(String[] args)
{
MyyThread mt = new MyyThread("F1 Thread");
MyyThread mt2 = new MyyThread("F2 Thread");
mt.start();
mt2.start();
}
}
-----------------------------------------------------------
output:
---------
F1 Thread ..got lock and performing safe operation.
F2 Thread ..unable to get lock and performing alternative operation.
No comments:
Post a Comment