The Lock Lock

  • Starting with JDK5.0, Java provides a more powerful thread synchronization mechanism — synchronization is achieved by explicitly defining a synchronization lock object. A synchronous Lock is acted by using a Lock object.
  • Java. Util. Concurrent. The locks. Lock interface is the tool of control multiple threads to Shared resources access. A Lock provides exclusive access to a shared resource. Only one thread at a time can Lock the Lock object. The thread must acquire the Lock object before starting to access the shared resource.
  • The ReentrantLock class implements Lock, which has the same concurrency and memory semantics as synchronized. In implementing thread-safe control, ReentrantLock is commonly used to explicitly Lock and release locks.

Synchronized versus Lock

  • Lock is an explicit Lock (manually open and close the Lock, don’t forget to close the Lock) synchronized is an implicit Lock, except that the scope is automatically released.
  • Lock has only code block locks, synchronized has code block locks and method locks.
  • With Lock locks, the JVM takes less time to schedule threads and performs better. And more extensible (more subclasses)
  • Priority order:
    1. Lock > Synchronize code block (already in method body, allocated resources) > Synchronize method (outside method body)
  • case
package com.Thread.lock; import java.util.concurrent.locks.ReentrantLock; public class TestLock { public static void main(String[] args) { Lock2 lock2 = new Lock2(); new Thread(lock2,"A").start(); new Thread(lock2,"B").start(); new Thread(lock2,"C").start(); } } class Lock2 implements Runnable{ int ticketsNum = 10; Private final ReentrantLock lock = new ReentrantLock(); @Override public void run() { while (true){ try { Thread.sleep(1000); The lock (); / / lock lock. If (ticketsNum > 0){system.out.println (thread.currentThread ().getName() +" ticketsNum-- +"); }else { break; } } catch (InterruptedException e) { e.printStackTrace(); }finally {// unlock lock.unlock(); }}}}Copy the code