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 acquire a lock at a time, and all access to shared resources requires the lock to be acquired first. However, some locks may allow concurrent access to shared resources, such as readwritelock (maintaining a pair of related locks, one for read-only operations and another for write operations).
1, Lock provides an unconditional, polling, timed, interruptible Lock acquisition operations, all lock and Unlock methods are explicit.
interruptedexception;
Boolean Trylock (); A timed and polling lock acquisition pattern
Boolean trylock (Long timeout,timeunit unit) throws interruptedexception;
void unlock (); Unlock
Condition newcondition ();
}
2, Reentrantlock implementation of the lock interface, compared with synchronized, Reentrantlock to deal with the use of the lock provides more flexibility.
3. Using the lock interface's canonical form requires that the lock Lock.unlock () be released in the finally block. If the lock-guarding code throws an exception outside of a try block, it will never be freed.
The following simulates lock usage: Suppose there are two threads (a thread, B thread) to call the print (String name) method, a thread is responsible for printing the ' Zhangsan ' string, and the B thread is responsible for printing the ' Lisi ' string.
1. When no lock is added for the print (String name) method, a thread is generated and the B thread has been executed, and the printed name appears as follows.
2, when a lock is added to the print (string name) method, the B thread executes the print (string name) method, or the synchronization effect, after a execution completes.
Package com.ljq.test.thread;
Import Java.util.concurrent.locks.Lock;
Import Java.util.concurrent.locks.ReentrantLock; /** * with lock instead of synchronized * * @author Administrator * */public class Locktest {public static void main (string[)
args) {new locktest (). Init ();
private void Init () {final Outputer outputer = new Outputer ();
A thread new thread (new Runnable () {@Override public void run () {while (true) {try {
Thread.Sleep (10);
catch (Interruptedexception e) {e.printstacktrace ();
} outputer.output ("Zhangsan");
}}). Start ();
b Thread new Thread (new Runnable () {@Override public void run () {while (true) {try {
Thread.Sleep (10);
catch (Interruptedexception e) {e.printstacktrace ();
} outputer.output ("Lisi");
}}). Start ();
} Static class Outputer {lock lock = new Reentrantlock ();
/** * Print Character * * @param name */public void output (String name) {int len = name.length ();
Lock.lock ();
try {for (int i = 0; i < len; i++) {System.out.print (Name.charat (i));
} System.out.println ();
finally {Lock.unlock ();
}
}
}
}