Synchronized和ReentrantLock有什么区别

本文通过三个不同的方法展示了如何确保多线程环境下变量操作的线程安全性。首先通过一个非线程安全的例子展示数据竞争的问题,然后分别介绍了使用synchronized关键字和ReentrantLock实现线程安全的两种方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

直接上代码

import org.junit.Test;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadSafeSample {

    public int sharedState1;
    public int sharedState2;
    public int sharedState3;

    public void nonSafeAction() {
        while (sharedState1 < 100000) {
            int former = sharedState1++;
            int latter = sharedState1;
            if (former != latter - 1) {
                System.out.println("[nonSafeAction] Observd data race,former is " + former + "" +
                        ", latter is " + latter);
            }
        }
    }

    public void safeAction() {
        while (sharedState2 < 100000) {
            //将两次赋值过程用 synchronized 保护起来,使用 this 作为互斥单元,
            // 就可以避免别的线程并发的去修改 sharedState
            synchronized (this) {
                int former = sharedState2++;
                int latter = sharedState2;
                if (former != latter - 1) {
                    System.out.println("[safeAction] Observd data race,former is " + former + "" +
                            ", latter is " + latter);
                }
            }
        }
    }

    public void safeAction2() {
        //创建公平锁
        ReentrantLock fairLock = new ReentrantLock(true);
        if(fairLock.tryLock()){
            try {
                while (sharedState3 < 100000) {
                    synchronized (this) {
                        int former = sharedState3++;
                        int latter = sharedState3;
                        if (former != latter - 1) {
                            System.out.println("[safeAction] Observd data race,former is " + former + "" +
                                    ", latter is " + latter);
                        }
                    }
                }
            } finally {
                fairLock.unlock();
            }
        }
    }


    @Test
    public void testNonSafeAction() throws  Exception{
        final ThreadSafeSample threadSafeSample = new ThreadSafeSample();
        Thread threadA = new Thread() {
            public void run() {
                threadSafeSample.nonSafeAction();
            }
        };

        Thread threadB = new Thread() {
            public void run() {
                threadSafeSample.nonSafeAction();
            }
        };

        threadA.start();
        threadB.start();
        threadA.join();
        threadB.join();
    }

    @Test
    public void testSafeAction() throws  Exception{
        final ThreadSafeSample threadSafeSample = new ThreadSafeSample();
        Thread threadA = new Thread() {
            public void run() {
                threadSafeSample.safeAction();
            }
        };

        Thread threadB = new Thread() {
            public void run() {
                threadSafeSample.safeAction();
            }
        };

        threadA.start();
        threadB.start();
        threadA.join();
        threadB.join();
    }

    @Test
    public void testSafeAction2() throws  Exception{
        final ThreadSafeSample threadSafeSample = new ThreadSafeSample();
        Thread threadA = new Thread() {
            public void run() {
                threadSafeSample.safeAction2();
            }
        };

        Thread threadB = new Thread() {
            public void run() {
                threadSafeSample.safeAction2();
            }
        };

        threadA.start();
        threadB.start();
        threadA.join();
        threadB.join();
    }
}
synchronized ReentrantLock 都是 Java 中用于实现同步的机制,二者有以下区别: 1. 实现方式不同:synchronized 是内置的 Java 关键字,而 ReentrantLock 是基于 Java.util.concurrent 包中的 Lock 接口实现的。 2. 锁的获取方式不同:synchronized 关键字在获取锁时是隐式进行的,程序员无法控制,而 ReentrantLock 则是显式获取锁,程序员可以通过 lock() 方法进行获取。同时,ReentrantLock 还提供了 tryLock() 方法,可以尝试获得锁,如果锁已经被其他线程持有,则返回 false,而不是一直等待。 3. 可重入性不同:synchronized 是可重入锁,也就是说,如果一个线程已经获得了某个对象的锁,那么它可以重复地进入由该对象的同步方法或同步代码块组成的代码区域,而不会被阻塞。而 ReentrantLock 也是可重入锁,但是需要注意释放锁的次数必须获取锁的次数相同,否则会导致死锁。 4. 等待可中断性不同:synchronized 关键字在获取锁时,如果锁已经被其他线程占用,那么当前线程就会一直等待,直到锁被释放。而 ReentrantLock 在获取锁时,可以设置等待超时时间,如果等待超时,当前线程就会退出等待。 5. 公平性不同:synchronized 关键字不提供公平性保证,也就是说,获取锁的线程是随机的。而 ReentrantLock 可以通过构造函数指定是否公平,如果设置为公平锁,则获取锁的线程按照请求的顺序获取锁。 6. 锁的释放方式不同:synchronized 关键字在执行完同步代码块或同步方法后,会自动释放锁。而 ReentrantLock 则需要手动调用 unlock() 方法释放锁,如果没有正确地释放锁,可能会导致死锁等问题。 综上所述,synchronized ReentrantLock 都可以用于实现同步,但是 ReentrantLock 提供了更多的灵活性控制力,可以根据需要设置不同的锁属性锁控制,但是使用也更为复杂,而 synchronized 则使用简单,但是灵活性不够。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值