Sychronized
Lock the code block and execute the code block.
Release Lock:
1. The thread that gets the lock finishes executing and releases the lock's possession
2. Execution exception occurs, the JVM lets the thread automatically release the lock
Disadvantages:
1. Exceptions will only be thrown, cannot be resolved, maintenance system is normal
Lock
public interface lock{
void lock ();//Gets the lock, the lock is fetched by another thread, waits
void Lockinterruptibly () throws interruptedexception;
Boolean trylock ();//success->true;fail->false
Boolean Trylock (long time,timeunit unit) throws Interruptedexception;
void unlock ();
Condition newcondition ();
}
<lock () >
Lock Lock=new Reentrantlock ();//reentrantlock implements lock with the same concurrency and memory semantics
There is a lock-related get counter, a thread that owns the lock gets the lock again, +1,e.g. Exits the second synchronized block, does not release the lock, exits the first synchronized block, releases the lock
try{
}finally{
Lock.unlock ();//In Finally, ensure that the lock must be released
}
Lock must be released in finally, otherwise throws an exception
<trylock () >
Boolean Captured=lock.trylock ();
try{
}finally{
if (captured)
Lock.unlock ();
Else
...//not acquired to lock
}
<trylock (Long time,timeunit) throws Interruptedexception;>
try{
Boolean captured=trylock (2,timeunit.seconds);
}catch (Interrupedexception e) {
throw new RuntimeException (e);
}
try{
}finally{
if (captured)
Lock.unlock ();
Else
....}
See the interesting ... The locking mechanism used to traverse node passing through the node in the linked list
Come here first.
java-Concurrent-lock&&synchronized