Lock is a tool for controlling multiple threads to access shared resources. Generally, the lock provides exclusive visits to shared resources. There is only one thread to get a lock at a time. All access to shared resources needs to be obtained first. However, some locks may allow interviews with shared resources, such as ReadWritelock (maintaining a pair of related locks, one for read -only operation, and the other for writing operations).
1. LOCK provides unconditional, round -balanced, timing, interruptable lock acquisition operations, all locking and unlocking methods are explicit.
public interface lock {void lock (); // lock // priority consider response interruption, instead of responding to the lock -locking ordinary acquisition or repeat to Void Lockinterruptibly () Throws International ck (); // Time and wheels The lock acquisition mode BOOLEAN TRYLOCK (Long Timeout, TimeUnit Unit) Throws InterruptedException; Void Unlock (); // Unlock the connection newcondition ();}
2. ReentrantLock realizes the Lock interface. Compared with Synchronized, ReentrantLock provides more flexibility for processing unavailable locks.
3. The normative form of the lock interface requires the release lock.unlock () to release lock.unlock () in the Finally block. If the lock -guard code is abnormal outside TRY block, it will never be released.
The following simulation LOCK usage: Assuming that there are two threads (thread A, B thread) to call the Print (String name) method, thread A is responsible for printing the 'zhangsan' string, and thread B is responsible for printing 'Lisi' string.
1. When adding the lint (String name) method, the thread A has not been executed, and the B thread has begun to execute, then the printed name will have the following problems.
2. When the Print Name method is added to the lock, the PRINT (String name) method is executed after the A is completed after the execution is completed to achieve mutual exclusion or synchronization effect.
package com.ljq.test.thread; Import Java.util.Concurrent.locks.Locks; Import Java.util.concurrent.locks. AREENTRANTLOCK; Ized * * @Author Administrator * * */Public Class LockTest {PUBLIC Static Void Main (String [] ARGS) {New Locktest (). Init ();} Private void Init () {Final outPUTPUTPUTPUTER = New Outputer (); // A new runnable () { @ n Override Public Void Run () {While (TRUE) {Try {Thread.sleep (10);} Catch (InterruptedException E) {e.printstacktrace ();} haangsan ");}}}). Start (); // B thread new thread (new runnable () {@Override public void run () {While (true) {try {thread.sleep (10);} Catch (interruptedexception E) {E.Prin. tStacktrace (); } outputer.output ("lisi");}}). Start ();} static class outputer {lock lock = new reentrantLock (); 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 ();}}}}