Home  >  Article  >  Java  >  Lock usage examples in Java multi-threaded programming

Lock usage examples in Java multi-threaded programming

高洛峰
高洛峰Original
2017-01-05 15:58:191145browse

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

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

public interface Lock{
  void lock(); //加锁
  //优先考虑响应中断,而不是响应锁定的普通获取或重入获取
  void lockInterruptibly() throws InterruptedException;
  boolean tryLock(); //可定时和可轮询的锁获取模式
  boolean tryLock(long timeout,TimeUnit unit) throws InterruptedException;
  void unlock(); //解锁
  Condition newCondition();
}

2. ReentrantLock implements the lock interface. Compared with synchronized, ReentrantLock provides more flexibility for handling unavailable locks.
3. The canonical form of using the lock interface requires that the lock be released in the finally block lock.unlock(). If the code guarding the lock throws an exception outside the try block, it will never be released.

The following simulates Lock usage: Assume that there are two threads (A thread, B thread) to call the print(String name) method, A thread is responsible for printing the 'zhangsan' string, and B thread is responsible for printing the 'lisi' character string.
1. When the print(String name) method is not locked, it will happen that thread A has not completed execution and thread B has started execution. Then the printed name will have the following problems.

2. When the print(String name) method is locked, thread B will execute the print(String name) method only after A has completed execution, achieving mutual exclusion or synchronization effect.

package com.ljq.test.thread;
  
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
  
/**
 * 用Lock替代synchronized
 *
 * @author Administrator
 *
 */
public class LockTest {
  
  public static void main(String[] args) {
    new LockTest().init();
  }
  
  private void init() {
    final Outputer outputer = new Outputer();
    //A线程
    new Thread(new Runnable() {
      @Override
      public void run() {
        while (true) {
          try {
            Thread.sleep(10);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
          outputer.output("zhangsan");
        }
  
      }
    }).start();
  
    //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();
  
    /**
     * 打印字符
     *
     * @param name
     */
    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();
      }
    }
  }
}

For more articles related to examples of Lock usage in Java multi-threaded programming, please pay attention to the PHP Chinese website!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn