“This is the 14th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

Another way to solve concurrency problems is to Lock under JUC

From the JDK official documentation to see the implementation of Lock there are several classes, ReentrantLock, read, write Lock

Steps to Lock using Lock

  1. New a lock

  2. Lock (lock in front of business code block)

  3. Unlock (in Finaly)

Using Lock to test the demo written earlier, multiple threads competing for tickets caused concurrency problems

Public class TestLock {public static void main(String[] args) {// Concurrency: multiple threads operate on the same resource Ticket Ticket = new Ticket(); new Thread(() -> { for (int i = 0; i < 20; i++) { ticket.sale(); } },"A").start(); new Thread(() -> { for (int i = 0; i < 20; i++) { ticket.sale(); } },"B").start(); new Thread(() -> { for (int i = 0; i < 20; i++) { ticket.sale(); } },"C").start(); } } class Ticket { private int number = 20; Lock lock = new ReentrantLock(); public void sale() { lock.lock(); Catch (Exception e) {e.printStackTrace(); // Try {// business code} catch (Exception e) {e.printStackTrace(); } finally { lock.unlock(); } if (number > 0) {system.out.println (thread.currentThread ().getName() + "+" + "+" + "+" + "+"); }}}Copy the code

Running results:

Check the running result, no ticket is purchased by multiple threads, which proves that the lock is successful

The difference between synchronized and Lock

Previously, synchronized locking was also implemented to solve the problem of concurrency when multiple threads operate on the same individual resource. What is the difference between the two methods

  1. Synchronized is a built-in Java keyword and Lock is a Java class

  2. Synchronized cannot determine the status of obtaining a Lock. Lock can determine whether a Lock is obtained

  3. Synchronized automatically releases the Lock. You must manually release the Lock. If the Lock is not released, a deadlock occurs

  4. Synchronized Thread 2 waits until thread 1 has acquired the Lock. Lock does not necessarily wait. Lock has a tryLock() method that attempts to acquire the Lock

  5. Synchronized synchronized synchronized synchronized synchronized synchronized synchronized synchronized synchronized synchronized synchronized synchronized synchronized synchronized synchronized synchronized synchronized synchronized synchronized synchronized synchronized synchronized synchronized synchronized synchronized

  6. Synchronized is good for locking a small amount of synchronization code, and Lock is good for locking a large amount of synchronization code

Fair locks and unfair locks

Click ReentrantLock to view the source code to see how fair and unfair locks are created

Fair lock: the total literal meaning of the understanding, is that this lock is very fair, follow first come, last come

Unfair lock: Is unfair, allowing later to jump the queue (default is unfair lock)