Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/sun/misc/ConditionLock.java
38829 views
/*1* Copyright (c) 1994, 2005, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package sun.misc;2627/**28* ConditionLock is a Lock with a built in state variable. This class29* provides the ability to wait for the state variable to be set to a30* desired value and then acquire the lock.<p>31*32* The lockWhen() and unlockWith() methods can be safely intermixed33* with the lock() and unlock() methods. However if there is a thread34* waiting for the state variable to become a particular value and you35* simply call Unlock(), that thread will not be able to acquire the36* lock until the state variable equals its desired value. <p>37*38* @author Peter King39*/40public final41class ConditionLock extends Lock {42private int state = 0;4344/**45* Creates a ConditionLock.46*/47public ConditionLock () {48}4950/**51* Creates a ConditionLock in an initialState.52*/53public ConditionLock (int initialState) {54state = initialState;55}5657/**58* Acquires the lock when the state variable equals the desired state.59*60* @param desiredState the desired state61* @exception java.lang.InterruptedException if any thread has62* interrupted this thread.63*/64public synchronized void lockWhen(int desiredState)65throws InterruptedException66{67while (state != desiredState) {68wait();69}70lock();71}7273/**74* Releases the lock, and sets the state to a new value.75* @param newState the new state76*/77public synchronized void unlockWith(int newState) {78state = newState;79unlock();80}81}828384