Search code examples
javamultithreadingconcurrencyjava.util.concurrentreentrantlock

ReentrantLock is not showing expected result


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

Solution

  • 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();