0

Where is the problem? ReentrantLock is not showing expected result. Two threads are executing same time rather than waiting one thread.

class MyThread2 extends Thread{
    String name;
    ReentrantLock reentrantLock = new ReentrantLock();
    MyThread2(String name){
        this.name = name;
    }
    public void run(){
        do {
            try {
                if (reentrantLock.tryLock(20,TimeUnit.MILLISECONDS)){
                    System.out.println("executing : "+ name);
                    Thread.sleep(500);
                    reentrantLock.unlock();
                    break;
                }else {
                    System.out.println("waiting "+ name);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }while (true);
    }
}

public class LockDemo2{
    public static void main(String[] args) {
        new MyThread2("Thread - 1").start();
        new MyThread2("Thread - 2").start();
    }
}

output:

executing : Thread - 1
executing : Thread - 2
xingbin
  • 27,410
  • 9
  • 53
  • 103
emon
  • 1,629
  • 1
  • 17
  • 18

2 Answers2

5

You should use the same ReentrantLock in different threads, instead creating different locks.

Change the constructor to this :

ReentrantLock reentrantLock;
MyThread2(String name, ReentrantLock lock){
    this.name = name;
    this.reentrantLock = lock;
}

And pass the same lock to them:

ReentrantLock lock = new ReentrantLock();
new MyThread2("Thread - 1", lock).start();
new MyThread2("Thread - 2", lock).start();
xingbin
  • 27,410
  • 9
  • 53
  • 103
1

You are using two different ReentrantLock on two different threads. @user6690200 solution is correct of using the same lock via the constructor.

Another solution is you can change your ReentrantLock to:

private static final ReentrantLock reentrantLock = new ReentrantLock();

So that each instance of a different thread will always share only one object of your ReentrantLock.

Gurinder
  • 943
  • 2
  • 9
  • 19