Shoaib Ali Shoaib Ali - 20 days ago 5
Java Question

Instead of using synchronized keyword i am using lock concept but i am not getting the output as i got in synchronized key word?

import java.util.concurrent.locks.ReentrantLock;

class Displayx
{
public void wish(String name)
{
ReentrantLock lock = new ReentrantLock();
//using locks
lock.lock();
for (int i = 0; i < 10; i++)
{
System.out.print("Good Morning : ");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
System.out.println("I got intruppted");
}
System.out.println(name);
}
lock.unlock();
}
}
class MyThreadex2 extends Thread
{
Displayx d;
String name;
public MyThreadex2(Displayx d, String name)
{
this.d = d;
this.name = name;
}
@Override
public void run()
{
d.wish(name);
}
}
public class ReentrantLockDemo1 {

public static void main(String[] args)
{
Displayx d = new Displayx();
MyThreadex2 mt1 = new MyThreadex2(d, "SHOAIB");
MyThreadex2 mt2 = new MyThreadex2(d, "RAHUL");

mt1.start();
mt2.start();

}

}


output i am getting is

Good Morning : Good Morning : SHOAIB
Good Morning : RAHUL
Good Morning : RAHUL
Good Morning : SHOAIB
Good Morning : SHOAIB
Good Morning : RAHUL
Good Morning : RAHUL
Good Morning : SHOAIB
Good Morning : SHOAIB
Good Morning : RAHUL
Good Morning : SHOAIB
Good Morning : RAHUL
Good Morning : SHOAIB
Good Morning : RAHUL
Good Morning : RAHUL
Good Morning : SHOAIB
Good Morning : SHOAIB
Good Morning : RAHUL
Good Morning : RAHUL
SHOAIB

Answer

Move ReentrantLock lock = new ReentrantLock(); outside of your method.

ReentrantLock lock = new ReentrantLock();
         public void  wish(String name)
         {
             //using locks
             lock.lock();
             try {
                 for (int i = 0; i < 10; i++) {
                     System.out.print("Good Morning : ");
                     try {
                         Thread.sleep(2000);
                     } catch (InterruptedException e) {
                         System.out.println("I got intruppted");
                     }
                     System.out.println(name);
                 } 
             } finally {
                 lock.unlock();
             }

         }