问题
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