【图解Java多线程设计模式】Read-Write Lock模式

在Read-Write Lock模式中,读取操作和写入操作是分开考虑的。在执行读取操作之前,线程必须获取用于读取的锁。而在执行写入操作之前,线程必须获取用于写入的锁。
由于当线程执行读取操作时,实例的状态不会发生变化,所以多个线程可以同时读取。但在读取时,不可以写入。
当线程执行写入操作时,实例的状态就会发生变化。因此,当有一个线程正在写入时,其他线程不可以读取或写入。
一般来说,执行互斥处理会降低程序性能。但如果把针对写入的互斥处理和针对读取的互斥处理分开来考虑,则可以提高程序性能。

示例

多个线程对Data类的实例执行读写操作。

类图

F2rQ2Q.png

Main.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Main {

public static void main(String[] args) {
Data data = new Data(10);
new ReaderThread(data).start();
new ReaderThread(data).start();
new ReaderThread(data).start();
new ReaderThread(data).start();
new ReaderThread(data).start();
new ReaderThread(data).start();
new WriterThread(data, "ABCDEFGHIJKLMNOPQRSTUVWXYZ").start();
new WriterThread(data, "abcdefghijklmnopqrstuvwxyz").start();
}
}

Data.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
public class Data {
private char[] buffer;
private ReadWriteLock lock = new ReadWriteLock();

public Data(int size) {
this.buffer = new char[size];

for (int i = 0; i < buffer.length; i++) {
buffer[i] = '*';
}
}

public char[] read() throws InterruptedException {
lock.readLock();

try {
return doRead();
} finally {
lock.readUnlock();
}
}

public void write(char c) throws InterruptedException {
lock.writeLock();

try {
doWrite(c);
} finally {
lock.writeUnlock();
}
}

private char[] doRead() {
char[] newbuf = new char[buffer.length];

for (int i = 0; i < buffer.length; i++) {
newbuf[i] = buffer[i];
}

slowly();
return newbuf;
}

private void doWrite(char c) {
for (int i = 0; i < buffer.length; i++) {
buffer[i] = c;
slowly();
}
}

private void slowly() {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
}
}

WriterThread.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import java.util.Random;

public class WriterThread extends Thread {
private final Data data;
private final String filler;
private int index = 0;
private static final Random random = new Random();

public WriterThread(Data data, String filler) {
this.data = data;
this.filler = filler;
}

public void run() {
try {
while (true) {
char c = nextchar();
data.write(c);
Thread.sleep(random.nextInt(3000));
}
} catch (InterruptedException e) {
}
}

private char nextchar() {
char c = filler.charAt(index);
index++;

if (index >= filler.length()) {
index = 0;
}

return c;
}
}

ReaderThread.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class ReaderThread extends Thread {
private final Data data;

public ReaderThread(Data data) {
this.data = data;
}

public void run() {
try {
while (true) {
char[] readbuf = data.read();
System.out.println(Thread.currentThread().getName() + " reads " + String.valueOf(readbuf));
}
} catch (InterruptedException e) {
}
}
}

ReadWriteLock.java

为了确保安全性,必须防止如下两种冲突。

  • “读取”和“写入”的冲突(read-write conflict)
  • “写入”和“写入”的冲突(write-write conflict)

当线程想要获取用于读取的锁时:

  • 如果有线程正在执行写入,则等待。否则,会引起read-write conflict。
  • 如果有线程正在执行读取,则无需等待。read-read不会引起conflict。

当线程想要获取用于写入的锁时:

  • 如果有线程正在执行写入,则等待。否则,会引起write-write conflict。
  • 如果有线程正在执行读取,则等待。否则,会引起read-write conflict。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
public final class ReadWriteLock {
private int readingReaders = 0;
private int waitingWriters = 0;
private int writingWriters = 0;
private boolean preferWriter = true;

public synchronized void readLock() throws InterruptedException {
while (writingWriters > 0 || (preferWriter && waitingWriters > 0)) {
wait();
}

readingReaders++;
}

public synchronized void readUnlock() {
readingReaders--;
preferWriter = true;
notifyAll();
}

public synchronized void writeLock() throws InterruptedException {
waitingWriters++;

try {
while (readingReaders > 0 || writingWriters > 0) {
wait();
}
} finally {
waitingWriters--;
}

writingWriters++;
}

public synchronized void writeUnlock() {
writingWriters--;
preferWriter = false;
notifyAll();
}
}

运行结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
Thread-0 reads **********
Thread-4 reads **********
Thread-5 reads **********
Thread-2 reads **********
Thread-1 reads **********
Thread-3 reads **********
Thread-2 reads AAAAAAAAAA
Thread-4 reads AAAAAAAAAA
Thread-3 reads AAAAAAAAAA
Thread-5 reads AAAAAAAAAA
Thread-0 reads AAAAAAAAAA
Thread-1 reads AAAAAAAAAA
Thread-0 reads aaaaaaaaaa
Thread-2 reads aaaaaaaaaa
Thread-1 reads aaaaaaaaaa
Thread-3 reads aaaaaaaaaa
Thread-5 reads aaaaaaaaaa
Thread-4 reads aaaaaaaaaa
Thread-0 reads aaaaaaaaaa
Thread-2 reads aaaaaaaaaa
Thread-5 reads aaaaaaaaaa
...
Thread-3 reads BBBBBBBBBB
Thread-5 reads BBBBBBBBBB
Thread-4 reads BBBBBBBBBB
Thread-2 reads BBBBBBBBBB
Thread-1 reads BBBBBBBBBB
Thread-0 reads BBBBBBBBBB
Thread-2 reads CCCCCCCCCC
Thread-0 reads CCCCCCCCCC
Thread-5 reads CCCCCCCCCC
Thread-1 reads CCCCCCCCCC
Thread-4 reads CCCCCCCCCC
Thread-3 reads CCCCCCCCCC
Thread-4 reads CCCCCCCCCC
Thread-2 reads CCCCCCCCCC
Thread-3 reads CCCCCCCCCC

登场角色

Reader(读者)

Reader角色对SharedResource角色执行read操作。在示例程序中,由ReaderThread类扮演此角色。

Writer(写者)

Writer角色对SharedResource角色执行write操作。在示例程序中,由WriterThread类扮演此角色。

SharedResource(共享资源)

SharedResource角色表示的是Reader角色和Writer角色二者共享的资源。SharedResource角色提供不修改内部状态的操作(read)和修改内部状态的操作(write)。在示例程序中,由Data类扮演此角色。

ReadWriteLock(读写锁)

ReadWriteLock角色提供了SharedResource角色实现read操作和write操作时所需的锁。即实现read操作时所需的readLock和readUnlock,以及实现write操作时所需的writeLock和writeUnlock。在示例程序中,由ReadWriteLock类扮演此角色。

类图

F2s3WD.png

Timethreads图

Reader角色正在读取,Writer角色正在等待

F2sBY8.png

一个Writer角色正在写入,Reader角色和其他Writer角色正在等待

F2sDfS.png