forked from examplehub/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReadWriteLockExampleTest.java
More file actions
53 lines (46 loc) · 1.33 KB
/
ReadWriteLockExampleTest.java
File metadata and controls
53 lines (46 loc) · 1.33 KB
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
package com.examplehub.basics.thread;
import static org.junit.jupiter.api.Assertions.*;
import java.util.Arrays;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.junit.jupiter.api.Test;
class ReadWriteLockExampleTest {
static class Counter {
private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
private final Lock rLock = readWriteLock.readLock();
private final Lock wLock = readWriteLock.writeLock();
private final int[] counts = new int[10];
public void inc(int index) {
wLock.lock();
try {
counts[index] += 1;
} finally {
wLock.unlock();
}
}
public int[] get() {
rLock.lock();
try {
return Arrays.copyOf(counts, counts.length);
} finally {
rLock.unlock();
}
}
}
@Test
void test() throws InterruptedException {
Counter counter = new Counter();
for (int i = 0; i < 10; i++) {
int finalI = i;
new Thread(
() -> {
counter.inc(finalI);
System.out.println(Arrays.toString(counter.get()));
})
.start();
}
Thread.sleep(100);
assertEquals("[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]", Arrays.toString(counter.get()));
}
}