Example of Lock usage in Java multithreaded programming

  • 2020-04-01 03:50:28
  • OfStack

A lock is a tool that controls access to a Shared resource by multiple threads. Typically, a lock provides exclusive access to a Shared resource. Only one thread can acquire the lock at a time, and all access to the Shared resource requires the lock to be acquired first. However, some locks may allow concurrent access to Shared resources, such as ReadWriteLock(which maintains a pair of related locks, one for read-only operations and the other for write operations).

1. Lock provides unconditional, pollable, timed, interruptible Lock acquisition operations. All methods of locking and unlocking are explicit.


public interface Lock{
  void lock(); //lock
  //Priority is given to response interrupts rather than to normal access or reentry access to response locking
  void lockInterruptibly() throws InterruptedException;
  boolean tryLock(); //Timed and pollable lock acquisition mode
  boolean tryLock(long timeout,TimeUnit unit) throws InterruptedException;
  void unlock(); //unlock
  Condition newCondition();
}

2. ReentrantLock implements the lock interface, which provides more flexibility in dealing with unavailable locks than synchronized.
3. The canonical form of using the lock interface requires that the lock be released ina finally block. If the lock guard code throws an exception outside the try block, it will never be released.

The following usage of mock Lock: suppose there are two threads (thread A and thread B) to call the print(String name) method, thread A is responsible for printing the 'zhangsan' String, and thread B is responsible for printing the 'lisi' String.
1. When no lock is added to the print(String name) method, it will be generated that thread A has not finished execution and thread B has started execution, so the printed name will appear as follows.

2. When A lock is added to the print(String name) method, it will be generated that after the execution of A, B thread will execute the print(String name) method to achieve mutual exclusion or synchronization effect.


package com.ljq.test.thread;
 
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
 

public class LockTest {
 
  public static void main(String[] args) {
    new LockTest().init();
  }
 
  private void init() {
    final Outputer outputer = new Outputer();
    //A thread
    new Thread(new Runnable() {
      @Override
      public void run() {
        while (true) {
          try {
            Thread.sleep(10);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
          outputer.output("zhangsan");
        }
 
      }
    }).start();
 
    //Thread B
    new Thread(new Runnable() {
      @Override
      public void run() {
        while (true) {
          try {
            Thread.sleep(10);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
          outputer.output("lisi");
        }
 
      }
    }).start();
 
  }
 
  static class Outputer {
    Lock lock = new ReentrantLock();
 
    
    public 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();
      }
    }
  }
}


Related articles: