Lock lock = new ReentrantLock(); lock.lock(); //critical section lock.unlock();其功能被称为synchronized的替代,具有相同的语义、相同的功能。
The Lock interface has the following primary methods:
The lock() method locks the Lock instance if possible. If the Lock instance is already locked, the thread calling lock() is blocked until the Lock is unlocked.
The lockInterruptibly() method locks the Lock unless the thread calling the method has been interrupted. Additionally, if a thread is blocked waiting to lock the Lock via this method, and it is interrupted, it exits this method calls.
The tryLock() method attempts to lock the Lock instance immediately. It returns true if the locking succeeds, false if Lock is already locked. This method never blocks.
The tryLock(long timeout, TimeUnit timeUnit) works like the tryLock() method, except it waits up the given timeout before giving up trying to lock the Lock.
The unlock() method unlocks the Lock instance. Typically, a Lock implementation will only allow the thread that has locked the Lock to call this method. Other threads calling this method may result in an unchecked exception (RuntimeException).
Lock lock = new ReentrantLock(); Conditon con = lock.newCondition(); // your code con.await();对于Condition常用的方法有awaite(),signal(),signalAll();分别对应Object对象中waite(),notify(),notifyall()。功能用法完全一样