0

If I have this code:

public class PrLock {
    private Lock lock1= new ReentrantLock();
    private Lock lock2= new ReentrantLock();
    private int num=0;

    public void addLock1(){
        lock1.lock();
        try {
            num++;
            System.out.println(Thread.currentThread().getName()+" NUM "+num);
        } finally{
            lock1.unlock();
        }
    }
    public void addLock2() {
        lock2.lock();
        try {
            num++;
            System.out.println(Thread.currentThread().getName()+" NUM "+num);
        } finally{
            lock2.unlock();
        }
    }
}

What is the difference between lock1 and lock2, is it a simple alias or is there a different logic?

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332

1 Answers1

0

If you would use one lock for those two methods you won't be able to execute them concurrently.

So having two locks means, while executing addLock1() from Thread-A you can execute addLock2() from Thread-B. Thread-B will be blocked, if you had one lock.

Mustafa
  • 401
  • 2
  • 7