Lock保持线程而不获取锁定

时间:2017-12-04 16:55:44

标签: java multithreading

我有一个

ReentrantLock lock = new ReentrantLock();

和2种方法

public void m1(){
        lock.lock();
        try {
            System.out.println("m1");
        } finally {
            lock.unlock();
        }
}

public void m2(){
        lock.lock();
        try {
            System.out.println("m2");
        } finally {
            lock.unlock();
        }
}

我只希望方法m2保持锁定而m1只检查锁是否被保持然后等到解锁并执行代码,但我不希望m1获得任何锁定。

例如:

T1 -> m1 // no lock acquired
T2 -> m1 // no lock acquired
T3 -> m2 // lock acquired
T4 -> m1 // wait until T3 finish executing m2 then execute m1

2 个答案:

答案 0 :(得分:0)

一种方法是使用Condition并等待布尔值直到条件为真

Condition methodM2finished= lock.newCondition();
boolean m2done=false;
方法m1中的

public void m1(){
        lock.lock();
        try {
         while(!m2done){//wait till this flag becomes true
           try{
                methodM2finished.await();
              }
           catch(InterruptedException e){
               e.printStackTrace();
            }
         }
            System.out.println("m1");
        } finally {
            lock.unlock();
        }
}

并且在m2

public void m2(){
        lock.lock();
        try {
            System.out.println("m2");
            //after all the business logic is done
           m2done=true;
           methodM2finished.signalAll();
        } finally {
            lock.unlock();
        }
}

答案 1 :(得分:0)

只需重新排序语句:

public void m1(){
  lock.lock(); 
  // No need for finally, no statement to complete abnormally.
  lock.unlock();

  System.out.println("m1");
}

当然,这将获得锁定;但它会立即再次释放它;所以在打印声明时不会锁定。