Java并发包--ReentrantLock

Java并发包–ReentrantLock

Java的线程安全,除了基本的同步锁以外,Jdk还为开发者提供了各种同步控制工具,如ReentrantLock,位于java.util.concurrent.locks包下的同步锁工具。

Java并发包--ReentrantLock_第1张图片

  1. 可重入
    拿几次lock,就需要释放几次。

    package com.borderxlab.concurrent.locks.reentrantlock;
    
    import java.util.concurrent.locks.ReentrantLock;
    
    public class ReenterLock implements Runnable {
        public static ReentrantLock lock = new ReentrantLock();
        public static int i = 0;
    
        @Override
        public void run() {
          for (int j = 0; j < 10000; j ++) {
            lock.lock();
            lock.lock();
            try {
              i ++;
            } finally {
              lock.unlock();
              lock.unlock();
            }
          }
        }
    
        public static void main(String[] args) throws InterruptedException {
          ReenterLock r = new ReenterLock();
          Thread t1 = new Thread(r);
          Thread t2 = new Thread(r);
          t1.start();
          t2.start();
          t1.join();
          t2.join();
          System.out.println(i);
        }
    }
  2. 可中断

  3. 可限时

  4. 公平锁

你可能感兴趣的:(java)