JDK Documentation Description:
Public Interfacethe Locklock implementation provides more than the use ofsynchronizedmethods and statements to obtain a wider range of locking operations. This implementation allows for a more flexible structure that can have very different properties and can support multiple related Condition objects. A lock is a tool that controls the access of multiple threads to a shared resource. Typically, a lock provides exclusive access to a shared resource. Only one thread can get a lock at a time, and all access to the shared resource requires a lock first. However, some locks may allow concurrent access to shared resources, such as read locks for Readwritelock. synchronizedthe use of a method or statement provides access to an implicit monitor lock associated with each object, but forces all lock acquisition and deallocation to appear in a block structure: When multiple locks are acquired, they must be disposed in reverse order, and all locks must be released in the same lexical scope as all locks are fetched. AlthoughsynchronizedThe scope mechanism of methods and statements makes it much easier to program with monitor locks, but it also helps to avoid many common programming errors involving locks, but sometimes requires a more flexible way to use locks. For example, some algorithms that traverse the data results of concurrent access require the use of "Hand-over-hand" or "Chain locking": Gets the lock of node A, then acquires the lock of node B, then releases A and obtains C, then releases B and obtains D, and so on. The implementation of the lock interface allows locks to be acquired and freed within different scopes, and allows multiple locks to be acquired and freed in any order, thereby supporting the use of this technique. With the increase of flexibility, it also brings more responsibility. Use is lost without a block structure locksynchronizedthe lock auto-release feature that occurs when the method and the statement are In most cases, the following statement should be used: Lock l= ...; L.lock (); Try { //access the resource protected by this lock}finally{l.unlock (); When locking and unlocking occurs in different scopes, you must be careful to ensure that all code that is executed when the lock is heldTry-finallyOrTry-Catchbe protected to ensure that the lock is released when necessary. The Lock implementation provides the usesynchronizedOther features that are not available in the methods and statements include a GET lock attempt (Trylock ()) for a non-block structure, an attempt to get an interruptible lock (lockinterruptibly ()), and an attempt to obtain a timeout failure lock (Trylock (Long, Timeunit)). The lock class can also provide a completely different behavior and semantics than an implicit monitor lock, such as guaranteed sorting, non-reentrant usage, or deadlock detection. If an implementation provides such a special semantics, the implementation must record these semantics. Note that the Lock instance is just an ordinary object, which itself can besynchronizedused as a target in the statement. Obtaining the monitor lock for a lock instance has no special relationship with any lock () method that invokes the instance. To avoid confusion, it is recommended that you never use a Lock instance in this way, except in its own implementation. Unless otherwise noted, pass for any parameterNULLValue will cause the NullPointerException to be thrown.
Sub-class:
Methods of Reentrantlock:
Method Summary |
int |
getHoldCount() Query the number of times that the current thread has retained this lock. |
protected Thread |
getOwner() Returns the thread that currently owns this lock, if the lock is not owned by any thread null . |
protected Collection<Thread> |
getQueuedThreads() Returns a collection that contains the thread that may be waiting to acquire this lock. |
int |
getQueueLength() Returns the estimated number of threads that are waiting to acquire this lock. |
protected Collection<Thread> |
getWaitingThreads(Condition condition) Returns a collection that contains those threads that may be waiting for a given condition related to this lock. |
int |
getWaitQueueLength(Condition condition) Returns the number of thread estimates waiting for the given condition associated with this lock. |
boolean |
hasQueuedThread(Thread thread) Queries whether a given thread is waiting to acquire this lock. |
boolean |
hasQueuedThreads() Query whether some threads are waiting to acquire this lock. |
boolean |
hasWaiters(Condition condition) Query whether some threads are waiting for a given condition related to this lock. |
boolean |
isFair() Returns if the fairness of this lock is set to True true . |
boolean |
isHeldByCurrentThread() Queries whether the current thread holds this lock. |
boolean |
isLocked() Queries whether this lock is persisted by any thread. |
void |
lock() Gets the lock. |
void |
lockInterruptibly() Gets the lock if the current thread is not interrupted. |
Condition |
newCondition() Returns the instance used with this Lock instance Condition . |
String |
toString() Returns a string that identifies the lock and its lock status. |
boolean |
tryLock() The lock is acquired only if the lock is not persisted by another thread at the time of the call. |
boolean |
tryLock(long timeout, TimeUnit unit) If the lock is not persisted by another thread within a given wait time and the current thread is not interrupted, the lock is acquired. |
void |
unlock() An attempt was made to release this lock. |
I'm going to use reentrantlock to rewrite some of the code in http://www.cnblogs.com/yangzhilong/p/4752480.html.
PackageCom.yzl;ImportJava.util.concurrent.locks.Lock;ImportJava.util.concurrent.locks.ReentrantLock; Public classThreadpart_lock { Public Static voidMain (string[] args) {testlock (); } /*** Using the same lock for the same object * this time with lock instead of the lock object pointed to by synchronized, * It is not important to be the same work object, is the same lock on the line, you can be outside the new same lock and then passed to the write party method to achieve the same effect **/ Private Static voidTestlock () {FinalWork work =NewThreadpart_lock. Work (); Thread Thread=NewThread (NewRunnable () {@Override Public voidrun () { while(true) {Work.write ("Wangwu"); } } }); Thread.Start (); Thread Thread1=NewThread (NewRunnable () {@Override Public voidrun () { while(true) {Work.write ("Zhangsan"); } } }); Thread1.start (); } Static classWork {lock lock=NewReentrantlock (); Public voidWrite (String name) {//synchronized (this) {Lock.lock (); Try{ for(inti=0; I<name.length (); i++) {System.out.print (Name.charat (i)); if(i = = (Name.length ()-1) {System.out.print ("\ n"); } } }finally{ //to prevent the lock from releasing after an exception occursLock.unlock (); } //} } }}
12, Java5 lock Java.util.concurrent.locks.Lock Reentrantlock