返回

探索并发之ReentrantLock的强大功能

后端

ReentrantLock与synchronized的比较

特性 ReentrantLock synchronized
可中断
可设置超时时间
可设置为公平锁
支持多个条件变量

ReentrantLock的特性

  • 可中断:ReentrantLock的lock()方法可以被中断,这意味着如果一个线程在等待获取锁时被中断,那么它将不会继续等待,而是会抛出InterruptedException异常。
  • 可设置超时时间:ReentrantLock的tryLock()方法可以设置超时时间,这意味着如果一个线程在等待获取锁时超过了指定的时间,那么它将不会继续等待,而是会返回false。
  • 可设置为公平锁:ReentrantLock可以设置为公平锁,这意味着当多个线程同时请求获取锁时,将按照请求的顺序来获取锁。
  • 支持多个条件变量:ReentrantLock支持多个条件变量,这意味着可以有多个线程同时等待同一个锁,当锁释放时,可以唤醒所有等待的线程。

ReentrantLock的使用示例

import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockExample {

    private static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {
        Thread thread1 = new Thread(() -> {
            lock.lock();
            try {
                System.out.println("Thread 1 acquired the lock");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                System.out.println("Thread 1 was interrupted");
            } finally {
                lock.unlock();
            }
        });

        Thread thread2 = new Thread(() -> {
            try {
                boolean success = lock.tryLock(500, TimeUnit.MILLISECONDS);
                if (success) {
                    System.out.println("Thread 2 acquired the lock");
                    Thread.sleep(1000);
                } else {
                    System.out.println("Thread 2 timed out");
                }
            } catch (InterruptedException e) {
                System.out.println("Thread 2 was interrupted");
            } finally {
                if (lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
        });

        Thread thread3 = new Thread(() -> {
            lock.lock();
            try {
                System.out.println("Thread 3 acquired the lock");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                System.out.println("Thread 3 was interrupted");
            } finally {
                lock.unlock();
            }
        });

        thread1.start();
        thread2.start();
        thread3.start();
    }
}

在上面的示例中,我们创建了一个ReentrantLock对象lock,并使用lock()、tryLock()和unlock()方法来演示ReentrantLock的特性。