我无法理解以下代码:
public class Counter {
private long value;
private Lock lock;
public long getAndIncrement() {
lock.lock();
try {
int temp = value;
value = value + 1;
} finally {
lock.unlock();
}
return temp;
}
}
我不明白的是,Lock 作为一个接口(interface)是如何实例化的? 如果它是实现 Lock 接口(interface)的匿名类,为什么我看不到 Lock 函数的任何重写(例如 lock() 和unlock() )?
简而言之,下面这行确实让我很困惑。
private Lock lock;
这里的锁是什么?它的类型是什么?
编辑:
Lock是一个接口(interface),无法实例化。查看构造函数后:
public Counter(){
lock = new ReentrantLock();
}
现在,一切都清楚了。 (感谢 Bhushan Uniyal)
最佳答案
问Lock作为一个接口(interface)是如何实例化的?
接口(interface)中的锁,由ReentrantLock、ReentrantReadWriteLock.ReadLock、ReentrantReadWriteLock.WriteLock实现
A reentrant mutual exclusion Lock with the same basic behavior and semantics as the implicit monitor lock accessed using synchronized methods and statements, but with extended capabilities.
A ReentrantLock is owned by the thread last successfully locking, but not yet unlocking it. A thread invoking lock will return, successfully acquiring the lock, when the lock is not owned by another thread. The method will return immediately if the current thread already owns the lock. This can be checked using methods isHeldByCurrentThread(), and getHoldCount().
The constructor for this class accepts an optional fairness parameter. When set true, under contention, locks favor granting access to the longest-waiting thread. Otherwise this lock does not guarantee any particular access order. Programs using fair locks accessed by many threads may display lower overall throughput (i.e., are slower; often much slower) than those using the default setting, but have smaller variances in times to obtain locks and guarantee lack of starvation. Note however, that fairness of locks does not guarantee fairness of thread scheduling. Thus, one of many threads using a fair lock may obtain it multiple times in succession while other active threads are not progressing and not currently holding the lock. Also note that the untimed tryLock method does not honor the fairness setting. It will succeed if the lock is available even if other threads are waiting.
Acquires the lock.
Acquires the lock if it is not held by another thread and returns immediately, setting the lock hold count to one.
If the current thread already holds the lock then the hold count is incremented by one and the method returns immediately.
If the lock is held by another thread then the current thread becomes disabled for thread scheduling purposes and lies dormant until the lock has been acquired, at which time the lock hold count is set to one.
关于Java锁解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43012544/