Lock a function from another function in java

丶灬走出姿态 提交于 2021-02-17 05:13:56

问题


I need lock a function from another function in java. In example above, I call slave function to print counter. And I need when that if master function called, all threads which calls slave function must be wait master functions to be ended.

How can I do that?

int counter = 0;

private void slave()
{
  System.out.println(counter);
}

private void master()
{
  lockSlave();
  counter ++;
  unlockSlave();
}

回答1:


Take a look at JDK ReentrantReadWriteLock.

private final ReadWriteLock lock = new ReentrantReadWriteLock();

private void slave()
{
    lock.readLock().lock();
    try {
        System.out.println(counter);
        ...
    } finally {
        lock.readLock().unlock();
    }
}

private void master()
{
    lock.writeLock().lock();
    try {
        counter ++;
        ...
    } finally {
        lock.writeLock().unlock();
    }
}



回答2:


Use a ReentrantReadWriteLock. Also make your variable volatile so changes can be seen by all threads.

ReadWriteLock m_lock = new ReentrantReadWriteLock();
Lock m_readLock = m_lock.readLock();
Lock m_writeLock = m_lock.writeLock();

volatile int counter = 0;

private void slave() {
  m_readLock.lock();
  try {
    System.out.println(counter);
  } finally {
    m_readLock.unlock();
  }
}

private void master(){
  m_writeLock.lock();
  try {
    counter ++;
  } finally {
    m_writeLock.unlock();
  }
}



回答3:


Use synchronized word, is what is for, you can synchronize the full method, so only one thread will be able to run at once.



来源:https://stackoverflow.com/questions/36279544/lock-a-function-from-another-function-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!