Skip to content

Lock接口

  • Lock 接口是 Java 并发包中的一个接口,它提供了比 synchronized 关键字更加灵活和强大的线程同步机制。
  • Lock 需要手动加锁和解锁,可以避免 synchronized 关键字可能出现的死锁问题。

ReentrantLock

  • ReentrantLock 是 Lock 接口的一个实现类,它是一个可重入的互斥锁,可以替代 synchronized 关键字实现线程同步。
  • ReentrantLock 提供了与 synchronized 关键字类似的功能,但是更加灵活和强大,可以实现更复杂的线程同步需求。
  • ReentrantLock 提供了一些高级功能,如可中断锁、公平锁、锁超时等。
  • ReentrantLock 的使用方式与 synchronized 关键字类似,但是需要手动加锁和解锁,需要注意避免死锁等问题。
java
public class ReentrantLockDemo {
    private Lock lock = new ReentrantLock();
    private int count = 0;

    public void increment() {
        lock.lock();
        try {
            count++;
        } finally {
            lock.unlock();
        }
    }

    public int getCount() {
        return count;
    }

    public static void main(String[] args) throws InterruptedException {
        ReentrantLockDemo demo = new ReentrantLockDemo();

        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                demo.increment();
            }
        });

        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                demo.increment();
            }
        });

        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();

        System.out.println("Count: " + demo.getCount());
    }
}