pro*_*tor 6

以下是三种方法,一种是访问锁的线程,另一种是用于放开锁的方法.您可能想尝试使用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)

  • 这基本上再现了```synchronized```,```````和```notify```行为.```ReentrantLock```和```Condition```清理了语义并允许公平,但其他方面大致相同. (2认同)

Mik*_*ike 0

不会,您通常不会看到行为上的差异。但正如该网站所说,在某些情况下您需要使用 aReentrantLock而不是synchronized

  1. 您希望等待线程被公平地选择。
  2. 您想使用 tryLock() 方法。
  3. 您想要中断正在等待的线程并让它执行其他操作。
  4. ReentrantLock的性能比synchronized要好,你关心这一点。

如果您不需要任何这些改进,使用synchronized就可以了,您可能无法区分其中的区别。