Java multi-threading series: show lock

A, Lock Interface

1, the core method:

  lock (): Gets lock
  unlock (): release the lock
  tryLock (long time, TimeUnit unit) : attempt to acquire the lock, you can set the timeout

2, the sample code

public  class LockDemo {

    // Lock the interface is a 
    Private Lock Lock = new new of ReentrantLock ();
     Private  int COUNT;
     public  int INCREMENT () {
         // lock 
        Lock . Lock ();
         the try {
            count++;
        } The finally {
             // must manually release the latch 
            Lock .unlock ();
        }
        return count;
    }
}

Second, the difference between Lock and synchronized

1, if you can set the timeout:
  you can set the timeout when Lock to acquire the lock. Synchronized while acquiring the lock is no timeout, it will always be there waiting for
2, can be interrupted:
  Lock acquiring the lock can be interrupted, synchronized can not be interrupted
3, release the lock mode:
  Use Lock, the lock must be manually released . synchronized release the lock to achieve the operating system level
4, is blocked:
  synchronized is the blocking of, tryLock is non-blocking
5, reentrancy:
  synchronized is reentrant lock (reentrant: a thread multiple times to acquire a lock ). Because the internal synchronized to record the number of locks acquired by a counter, each acquire a lock, the counter is incremented each release a lock 1, the counter is decremented by one.
  ReentrantLock also reentrant lock
6, whether it is fair:
  if in time, first obtain a lock request must first be satisfied, the lock is fair.
  Unfair locks generally higher efficiency. (In fairness, the thread will not get the lock queues and suspend, suspend the operation more if turn the thread to acquire a lock, the thread hangs need to lift before you can get a lock. Because lifted time-consuming, resulting in a fair lock is not efficient unfair locks do not line up).
  pending: the operating system can be understood as the current thread is removed from memory
constructor ReentrantLock can specify whether fair or unfair lock lock, the default unfair lock
7, whether the exclusive lock:
  exclusive lock: only one thread at a time to access
  synchronized and are exclusive lock ReentrantLock

Third, read-write locks

1. Definition: when the same time allows multiple threads simultaneously read access and write access to the thread, all reads and writes are blocked. For reading and writing little scenes. Internal maintains a read lock and a write lock

2, ReadWriteLock ReentrantReadWriteLock classes and interfaces:

Four, Condition

Guess you like

Origin www.cnblogs.com/inspred/p/11103767.html