以下是三种方法,一种是访问锁的线程,另一种是用于放开锁的方法.您可能想尝试使用synchronized
关键字实现这些.使用的扩展能力和优势ReentrantLock
将变得显而易见.
public class DoorLockUsingLock {
private int counter= 0;
private Thread owner= null;
private Lock l = new ReentrantLock();
private Condition notLocked= l.newCondition();
public void lockItDown() throws InterruptedException {
l.lockInterruptibly();
try {
while ((counter> 0) && (owner!= Thread.currentThread())) {
notLocked.await();
}
counter++;
owner = Thread.currentThread();
} finally {
l.unlock();
}
}
public void lockItDownUninterruptibly() {
l.lock();
try {
while ((counter > 0) && (owner != Thread.currentThread())) {
notLocked.awaitUninterruptibly();
}
counter++;
owner= Thread.currentThread();
} finally {
l.unlock();
}
}
public boolean tryLockItDown(long timeout, TimeUnit unit) throws InterruptedException {
long time = unit.toNanos(timeout);
long end = System.nanoTime() + time;
boolean success = l.tryLock(timeout, unit);
if (!success) {
return false;
}
try {
time = end- System.nanoTime();
while ((counter> 0) && (owner != Thread.currentThread()) && (time > 0)) {
notLocked.await(time, TimeUnit.NANOSECONDS);
time = end - System.nanoTime();
}
if (time > 0) {
counter++;
owner = Thread.currentThread();
return true;
}
return false;
} finally {
l.unlock();
}
}
public void unlockIt() throws IllegalMonitorStateException {
l.lock();
try {
if (counter== 0) {
throw new IllegalMonitorStateException();
}
if (owner!= Thread.currentThread()) {
throw new IllegalMonitorStateException();
}
counter--;
if (counter == 0) {
owner = null;
notLocked.signal();
}
} finally {
l.unlock();
}
}
}
Run Code Online (Sandbox Code Playgroud)
不会,您通常不会看到行为上的差异。但正如该网站所说,在某些情况下您需要使用 aReentrantLock
而不是synchronized
。
如果您不需要任何这些改进,使用synchronized
就可以了,您可能无法区分其中的区别。
归档时间: |
|
查看次数: |
7537 次 |
最近记录: |