Drop Down

Monday, January 6, 2020

TryLock game

package multithreading;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

class MyThread4 extends Thread
{
static ReentrantLock l = new ReentrantLock();
MyThread4(String name)
{
super(name);
}
@Override
public void run()
{
do
{
try {
if(l.tryLock(5000,TimeUnit.MICROSECONDS))
{
System.out.println(Thread.currentThread().getName()+" ..Got Lock and running safe code");
Thread.sleep(30000);
l.unlock();
System.out.println(Thread.currentThread().getName()+" ..Released the lock");
break;
}
else
{
System.out.println(Thread.currentThread().getName()+" ..Unable to get Lock and executing alternative code");
Thread.sleep(5000);
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
while(true);
}
}


public class ReentrantLock_Demo4
{

public static void main(String[] args)
{
MyThread4  mtt1 = new MyThread4("F1 Thread");
MyThread4  mtt2 = new MyThread4("F2 Thread");
mtt1.start();
mtt2.start();
}

}
----------------------------------
output
----------
F2 Thread ..Got Lock and running safe code
F1 Thread ..Unable to get Lock and executing alternative code
F1 Thread ..Unable to get Lock and executing alternative code
F1 Thread ..Unable to get Lock and executing alternative code
F1 Thread ..Unable to get Lock and executing alternative code
F1 Thread ..Unable to get Lock and executing alternative code
F1 Thread ..Unable to get Lock and executing alternative code
F2 Thread ..Released the lock
F1 Thread ..Got Lock and running safe code
F1 Thread ..Released the lock

No comments:

Post a Comment

Java 8 Notes Pics