Advanced Java (8) - Concurrent (multi-threaded Locks)

There are three types of locks, lock method, object lock, lock class. (Method lock object lock is a)
an object lock
object lock
public class Object {
Private Lock Lock of ReentrantLock new new = ();. JavaSE1.5 // add a package to support synchronous java.util.concurrent
public void Method () {
the synchronized (the this) {
System.out.println ( "I object lock");
}
}
}

public synchronized void method () {// use the default instance of this class as a lock
System.out.println ( "I am also a target lock method lock");
}
This mechanism ensures that the same time for each instance of the class, all of its declaration synchronized function as a member of only one executable, so as to effectively prevent the access member variables of class conflict

Second, the class lock
a static class variables and static loads only in memory and an initialization, once a static method is declared as the synchronized, all instances of such objects in this method is invoked, to share the same lock, called class lock.
A form:
public class Object {
public static void the synchronized Method () {
System.out.println ( "I was the first kind of lock");
}
}

Two forms:
public class Object {
public void Method () {
the synchronized (object.this) {
System.out.println ( "I was the second lock type");
}
}
}

Third, the class lock
ReentrantLock
Lock.lock () the current thread tries to acquire a lock if the lock acquisition is less than, the current thread will remain dormant until the lock is acquired.
Lock.lockInterruptibly () allow the current thread to acquire a lock, if the lock can with, directly or returns the current thread will remain dormant until about two cases in which a occurs:
the current thread to acquire the lock
. other thread interrupted the current thread interrupted the current thread acquires the lock operation is allowed
lock. tryLock () attempts to obtain a lock if the lock is available, the direct return ture, and to acquire the lock. otherwise, the direct return false
Lock.tryLock (Long time, TimeUnit Unit) tries to acquire a lock in a certain period of time, If the lock is available, the direct returns true, otherwise wait timeout return fasle
lock.unlock () to release the lock
Lock.newCondition ()

Guess you like

Origin blog.51cto.com/4397014/2436898