⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 reentrantlock.java

📁 java1.6众多例子参考
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
     *     * <li>Some other thread {@linkplain Thread#interrupt interrupts}     * the current thread; or     *     * <li>The specified waiting time elapses     *     * </ul>     *     * <p>If the lock is acquired then the value {@code true} is returned and     * the lock hold count is set to one.     *     * <p>If the current thread:     *     * <ul>     *     * <li>has its interrupted status set on entry to this method; or     *     * <li>is {@linkplain Thread#interrupt interrupted} while     * acquiring the lock,     *     * </ul>     * then {@link InterruptedException} is thrown and the current thread's     * interrupted status is cleared.     *     * <p>If the specified waiting time elapses then the value {@code false}     * is returned.  If the time is less than or equal to zero, the method     * will not wait at all.     *     * <p>In this implementation, as this method is an explicit     * interruption point, preference is given to responding to the     * interrupt over normal or reentrant acquisition of the lock, and     * over reporting the elapse of the waiting time.     *     * @param timeout the time to wait for the lock     * @param unit the time unit of the timeout argument     * @return {@code true} if the lock was free and was acquired by the     *         current thread, or the lock was already held by the current     *         thread; and {@code false} if the waiting time elapsed before     *         the lock could be acquired     * @throws InterruptedException if the current thread is interrupted     * @throws NullPointerException if the time unit is null     *     */    public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException {        return sync.tryAcquireNanos(1, unit.toNanos(timeout));    }    /**     * Attempts to release this lock.     *     * <p>If the current thread is the holder of this lock then the hold     * count is decremented.  If the hold count is now zero then the lock     * is released.  If the current thread is not the holder of this     * lock then {@link IllegalMonitorStateException} is thrown.     *     * @throws IllegalMonitorStateException if the current thread does not     *         hold this lock     */    public void unlock() {        sync.release(1);    }    /**     * Returns a {@link Condition} instance for use with this     * {@link Lock} instance.     *     * <p>The returned {@link Condition} instance supports the same     * usages as do the {@link Object} monitor methods ({@link     * Object#wait() wait}, {@link Object#notify notify}, and {@link     * Object#notifyAll notifyAll}) when used with the built-in     * monitor lock.     *     * <ul>     *     * <li>If this lock is not held when any of the {@link Condition}     * {@linkplain Condition#await() waiting} or {@linkplain     * Condition#signal signalling} methods are called, then an {@link     * IllegalMonitorStateException} is thrown.     *     * <li>When the condition {@linkplain Condition#await() waiting}     * methods are called the lock is released and, before they     * return, the lock is reacquired and the lock hold count restored     * to what it was when the method was called.     *     * <li>If a thread is {@linkplain Thread#interrupt interrupted}     * while waiting then the wait will terminate, an {@link     * InterruptedException} will be thrown, and the thread's     * interrupted status will be cleared.     *     * <li> Waiting threads are signalled in FIFO order.     *     * <li>The ordering of lock reacquisition for threads returning     * from waiting methods is the same as for threads initially     * acquiring the lock, which is in the default case not specified,     * but for <em>fair</em> locks favors those threads that have been     * waiting the longest.     *     * </ul>     *     * @return the Condition object     */    public Condition newCondition() {        return sync.newCondition();    }    /**     * Queries the number of holds on this lock by the current thread.     *     * <p>A thread has a hold on a lock for each lock action that is not     * matched by an unlock action.     *     * <p>The hold count information is typically only used for testing and     * debugging purposes. For example, if a certain section of code should     * not be entered with the lock already held then we can assert that     * fact:     *     * <pre>     * class X {     *   ReentrantLock lock = new ReentrantLock();     *   // ...     *   public void m() {     *     assert lock.getHoldCount() == 0;     *     lock.lock();     *     try {     *       // ... method body     *     } finally {     *       lock.unlock();     *     }     *   }     * }     * </pre>     *     * @return the number of holds on this lock by the current thread,     *         or zero if this lock is not held by the current thread     */    public int getHoldCount() {        return sync.getHoldCount();    }    /**     * Queries if this lock is held by the current thread.     *     * <p>Analogous to the {@link Thread#holdsLock} method for built-in     * monitor locks, this method is typically used for debugging and     * testing. For example, a method that should only be called while     * a lock is held can assert that this is the case:     *     * <pre>     * class X {     *   ReentrantLock lock = new ReentrantLock();     *   // ...     *     *   public void m() {     *       assert lock.isHeldByCurrentThread();     *       // ... method body     *   }     * }     * </pre>     *     * <p>It can also be used to ensure that a reentrant lock is used     * in a non-reentrant manner, for example:     *     * <pre>     * class X {     *   ReentrantLock lock = new ReentrantLock();     *   // ...     *     *   public void m() {     *       assert !lock.isHeldByCurrentThread();     *       lock.lock();     *       try {     *           // ... method body     *       } finally {     *           lock.unlock();     *       }     *   }     * }     * </pre>     *     * @return {@code true} if current thread holds this lock and     *         {@code false} otherwise     */    public boolean isHeldByCurrentThread() {        return sync.isHeldExclusively();    }    /**     * Queries if this lock is held by any thread. This method is     * designed for use in monitoring of the system state,     * not for synchronization control.     *     * @return {@code true} if any thread holds this lock and     *         {@code false} otherwise     */    public boolean isLocked() {        return sync.isLocked();    }    /**     * Returns {@code true} if this lock has fairness set true.     *     * @return {@code true} if this lock has fairness set true     */    public final boolean isFair() {        return sync instanceof FairSync;    }    /**     * Returns the thread that currently owns this lock, or     * {@code null} if not owned. When this method is called by a     * thread that is not the owner, the return value reflects a     * best-effort approximation of current lock status. For example,     * the owner may be momentarily {@code null} even if there are     * threads trying to acquire the lock but have not yet done so.     * This method is designed to facilitate construction of     * subclasses that provide more extensive lock monitoring     * facilities.     *     * @return the owner, or {@code null} if not owned     */    protected Thread getOwner() {        return sync.getOwner();    }    /**     * Queries whether any threads are waiting to acquire this lock. Note that     * because cancellations may occur at any time, a {@code true}     * return does not guarantee that any other thread will ever     * acquire this lock.  This method is designed primarily for use in     * monitoring of the system state.     *     * @return {@code true} if there may be other threads waiting to     *         acquire the lock     */    public final boolean hasQueuedThreads() {        return sync.hasQueuedThreads();    }    /**     * Queries whether the given thread is waiting to acquire this     * lock. Note that because cancellations may occur at any time, a     * {@code true} return does not guarantee that this thread     * will ever acquire this lock.  This method is designed primarily for use     * in monitoring of the system state.     *     * @param thread the thread     * @return {@code true} if the given thread is queued waiting for this lock     * @throws NullPointerException if the thread is null     */    public final boolean hasQueuedThread(Thread thread) {        return sync.isQueued(thread);    }    /**     * Returns an estimate of the number of threads waiting to     * acquire this lock.  The value is only an estimate because the number of     * threads may change dynamically while this method traverses     * internal data structures.  This method is designed for use in     * monitoring of the system state, not for synchronization     * control.     *     * @return the estimated number of threads waiting for this lock     */    public final int getQueueLength() {        return sync.getQueueLength();    }    /**     * Returns a collection containing threads that may be waiting to     * acquire this lock.  Because the actual set of threads may change     * dynamically while constructing this result, the returned     * collection is only a best-effort estimate.  The elements of the     * returned collection are in no particular order.  This method is     * designed to facilitate construction of subclasses that provide     * more extensive monitoring facilities.     *     * @return the collection of threads     */    protected Collection<Thread> getQueuedThreads() {        return sync.getQueuedThreads();    }    /**     * Queries whether any threads are waiting on the given condition     * associated with this lock. Note that because timeouts and     * interrupts may occur at any time, a {@code true} return does     * not guarantee that a future {@code signal} will awaken any     * threads.  This method is designed primarily for use in     * monitoring of the system state.     *     * @param condition the condition     * @return {@code true} if there are any waiting threads     * @throws IllegalMonitorStateException if this lock is not held     * @throws IllegalArgumentException if the given condition is     *         not associated with this lock     * @throws NullPointerException if the condition is null     */    public boolean hasWaiters(Condition condition) {        if (condition == null)            throw new NullPointerException();        if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))            throw new IllegalArgumentException("not owner");        return sync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject)condition);    }    /**     * Returns an estimate of the number of threads waiting on the     * given condition associated with this lock. Note that because     * timeouts and interrupts may occur at any time, the estimate     * serves only as an upper bound on the actual number of waiters.     * This method is designed for use in monitoring of the system     * state, not for synchronization control.     *     * @param condition the condition     * @return the estimated number of waiting threads     * @throws IllegalMonitorStateException if this lock is not held     * @throws IllegalArgumentException if the given condition is     *         not associated with this lock     * @throws NullPointerException if the condition is null     */    public int getWaitQueueLength(Condition condition) {        if (condition == null)            throw new NullPointerException();        if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))            throw new IllegalArgumentException("not owner");        return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject)condition);    }    /**     * Returns a collection containing those threads that may be     * waiting on the given condition associated with this lock.     * Because the actual set of threads may change dynamically while     * constructing this result, the returned collection is only a     * best-effort estimate. The elements of the returned collection     * are in no particular order.  This method is designed to     * facilitate construction of subclasses that provide more     * extensive condition monitoring facilities.     *     * @param condition the condition     * @return the collection of threads     * @throws IllegalMonitorStateException if this lock is not held     * @throws IllegalArgumentException if the given condition is     *         not associated with this lock     * @throws NullPointerException if the condition is null     */    protected Collection<Thread> getWaitingThreads(Condition condition) {        if (condition == null)            throw new NullPointerException();        if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))            throw new IllegalArgumentException("not owner");        return sync.getWaitingThreads((AbstractQueuedSynchronizer.ConditionObject)condition);    }    /**     * Returns a string identifying this lock, as well as its lock state.     * The state, in brackets, includes either the String {@code "Unlocked"}     * or the String {@code "Locked by"} followed by the     * {@linkplain Thread#getName name} of the owning thread.     *     * @return a string identifying this lock, as well as its lock state     */    public String toString() {        Thread o = sync.getOwner();        return super.toString() + ((o == null) ?                                   "[Unlocked]" :                                   "[Locked by thread " + o.getName() + "]");    }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -