Java 8 - juc - Lock和ReentrantLock

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Lock和ReentrantLock是用于提供显式锁机制的类,它们支持更灵活的并发控制。
 *
 * Lock接口定义了获取锁和释放锁的基本操作,它提供了比使用synchronized关键字更细粒度的控制。
 *
 * ReentrantLock是Lock接口的实现类,它是一个可重入锁,意味着同一个线程可以多次获取同一个锁而不会发生死锁。
 */
public class MyReentrantLockExample {
    
    
    private static final Lock lock = new ReentrantLock();
    private static int counter = 0;

    public static void main(String[] args) {
    
    
        Thread thread1 = new Thread(new Worker3());
        Thread thread2 = new Thread(new Worker3());

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

        try {
    
    
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }

        System.out.println("Counter: " + counter);
    }

    static class Worker3 implements Runnable {
    
    
        @Override
        public void run() {
    
    
            lock.lock(); // 获取锁

            try {
    
    
                for (int i = 0; i < 1000; i++) {
    
    
                    counter++;
                }
            } finally {
    
    
                lock.unlock(); // 释放锁
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_43116031/article/details/130937256
今日推荐