Java 基础
Java 容器
Java 并发
设计模式
目录

互斥同步

# 互斥同步

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

# synchronized

1. 同步一个代码块

public void func() {
    synchronized (this) {
        // ...
    }
}
1
2
3
4
5

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

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

package com.code.concurrent.example5;

public class SynchronizedExample {

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

    public void func2() {
        System.out.println("func2:");
        for (int i = 0; i < 10; i++) {
            System.out.print(i + " ");
        }
        System.out.println("");
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.code.concurrent.example5;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
    public static void main(String[] args) { 
        SynchronizedExample e1 = new SynchronizedExample();
        ExecutorService executorService = Executors.newCachedThreadPool();
        executorService.execute(() -> e1.func1());
        executorService.execute(() -> e1.func1());
        executorService.execute(() -> e1.func2());
        executorService.execute(() -> e1.func2());
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
func1:
func2:
func2:
0 1 2 3 4 5 0 1 2 3 0 6 1 2 3 4 5 6 7 8 4 5 6 7 8 9 
9 
7 8 9 
func1:
0 1 2 3 4 5 6 7 8 9 
1
2
3
4
5
6
7
8

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

package com.code.concurrent.example5;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main2 {
    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());
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
func1:
func1:
0 0 1 1 2 2 3 3 4 5 4 6 5 6 7 7 8 8 9 9 
1
2
3

2. 同步一个方法

public synchronized void func () {
    // ...
}
1
2
3

它和同步代码块一样,作用于同一个对象。

3. 同步一个类

public void func() {
    synchronized (SynchronizedExample.class) {
        // ...
    }
}
1
2
3
4
5

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

package com.code.concurrent.example6;

public class SynchronizedExample {
    public void func2() {
        synchronized (SynchronizedExample.class) {
            for (int i = 0; i < 10; i++) {
                System.out.print(i + " ");
            }
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
package com.code.concurrent.example6;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
    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());
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 
1

4. 同步一个静态方法

public synchronized static void fun() {
    // ...
}
1
2
3

作用于整个类。

# ReentrantLock

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

package com.code.concurrent.example7;

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

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(); // 确保释放锁,从而避免发生死锁。
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.code.concurrent.example7;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
    public static void main(String[] args) {
        LockExample lockExample = new LockExample();
        ExecutorService executorService = Executors.newCachedThreadPool();
        executorService.execute(() -> lockExample.func());
        executorService.execute(() -> lockExample.func());
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 
1

# 比较

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 会确保锁的释放。