聊一聊线程互斥与同步的那些事(以实例解释synchronized与ReentrantLock)

线程互斥与同步

结尾有彩蛋

Java 提供了两种锁机制来控制多个线程对共享资源的互斥访问,synchronized 由 JVM 实现, ,而另一个是 JDK 实现的 ReentrantLock。


synchronized

1. 同步一个代码块

public void func() {
    synchronized (this) {
        // 同步操作代码
    }
}

它只作用于同一个对象,如果调用两个对象上的同步代码块,就不会进行同步。

对于以下代码,使用 ExecutorService 执行了两个线程,由于调用的是同一个对象的同步代码块,因此这两个线程会进行同步,当一个线程进入同步语句块时,另一个线程就必须等待。
代码示例:

public class SynchronizedExample {

    public void func1() {
        synchronized (this) {
            for (int i = 0; i < 10; i++) {
                System.out.print(i + " ");
            }
        }
    }
}

使用两个线程打印序列:

public static void main(String[] args) {
    SynchronizedExample e1 = new SynchronizedExample();
    ExecutorService executorService = Executors.newCachedThreadPool();
    executorService.execute(() -> e1.func1());
    executorService.execute(() -> e1.func1());
}

打印结果:

0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9

对于以下代码,两个线程调用了不同对象的同步代码块,因此这两个线程就不需要同步。从输出结果可以看出,两个线程交叉执行。

public static void main(String[] args) {
    SynchronizedExample e1 = new SynchronizedExample();
    SynchronizedExample e2 = new SynchronizedExample();
    ExecutorService executorService = Executors.newCachedThreadPool();
    executorService.execute(() -> e1.func1());
    executorService.execute(() -> e2.func1());
}

执行结果:

0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9

2.同步一个方法

代码示例:

public synchronized void func () {
    // ...
}

3.同步一个类

代码示例:

public void func() {
    synchronized (SynchronizedExample.class) {
        // ...
    }
}

作用于整个类,也就是说两个线程调用同一个类的不同对象上的这种同步语句,也会进行同步。

public class SynchronizedExample {

    public void func2() {
        synchronized (SynchronizedExample.class) {
            for (int i = 0; i < 10; i++) {
                System.out.print(i + " ");
            }
        }
    }
}

声明两个对象,分别使用不用的线程打印:

public static void main(String[] args) {
    SynchronizedExample e1 = new SynchronizedExample();
    SynchronizedExample e2 = new SynchronizedExample();
    ExecutorService executorService = Executors.newCachedThreadPool();
    executorService.execute(() -> e1.func2());
    executorService.execute(() -> e2.func2());
}

执行结果:

0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9

4.同步一个静态方法

同步一个静态方法,会作用整个类,因此打印结果与上面同步整个类效果相同。

定义一个同步的静态方法:

public class SynchronizedExample1 {
    public synchronized static void fun(){
        for (int i = 0; i < 10; i++) {
            System.out.print(i + " ");
        }
    }
}

使用不同线程打印:

 public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        executorService.execute(() -> SynchronizedExample1.fun());
        executorService.execute(() -> SynchronizedExample1.fun());
    }

执行结果:

0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 

ReentrantLock

ReentrantLock 是 java.util.concurrent(J.U.C)包中的锁。

通过锁定义一个同步打印:

public class LockExample {

    private Lock lock = new ReentrantLock();

    public void func() {
        lock.lock();
        try {
            for (int i = 0; i < 10; i++) {
                System.out.print(i + " ");
            }
        } finally {
       	     // 确保释放锁,从而避免发生死锁。
            lock.unlock(); 
        }
    }
}

使用多线程调用:

public static void main(String[] args) {
    LockExample lockExample = new LockExample();
    ExecutorService executorService = Executors.newCachedThreadPool();
    executorService.execute(() -> lockExample.func());
    executorService.execute(() -> lockExample.func());
}

执行结果:

0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9

对比一下ReentrantLock与synchronized

  1. 实现方式不同。synchronized 是 JVM 实现的,而 ReentrantLock 是 JDK 实现的。
  2. 性能。新版本 Java 对 synchronized 进行了很多优化,例如自旋锁等,synchronized 与 ReentrantLock 大致相同。
  3. 等待可中断。当持有锁的线程长期不释放锁的时候,正在等待的线程可以选择放弃等待,改为处理其他事情。ReentrantLock 可中断,而 synchronized 不行。
  4. 公平锁。公平锁是指多个线程在等待同一个锁时,必须按照申请锁的时间顺序来依次获得锁。synchronized 中的锁是非公平的,ReentrantLock 默认情况下也是非公平的,但是也可以是公平的。
  5. 锁绑定多个条件。一个 ReentrantLock 可以同时绑定多个 Condition 对象。

使用建议:

如果你不需要使用 ReentrantLock 的高级功能,那么建议优先使用 synchronized。因为 synchronized 是 JVM 实现的一种锁机制,JVM 原生地支持它,而 ReentrantLock 不是所有的 JDK 版本都支持。并且使用 synchronized 不用担心没有释放锁而导致死锁问题,因为 JVM 会确保锁的释放。

彩蛋

在这里插入图片描述
超神学院语录:

兄弟,你只是个战士,不要想着那些,日天的事

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

keep-go-on

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值