forked from hellokaton/learn-java8
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLock5.java
More file actions
41 lines (33 loc) · 1.24 KB
/
Copy pathLock5.java
File metadata and controls
41 lines (33 loc) · 1.24 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
package io.github.biezhi.java8.concurrent;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.StampedLock;
public class Lock5 {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(2);
StampedLock lock = new StampedLock();
executor.submit(() -> {
long stamp = lock.tryOptimisticRead();
try {
System.out.println("Optimistic Lock Valid: " + lock.validate(stamp));
ConcurrentUtils.sleep(1);
System.out.println("Optimistic Lock Valid: " + lock.validate(stamp));
ConcurrentUtils.sleep(2);
System.out.println("Optimistic Lock Valid: " + lock.validate(stamp));
} finally {
lock.unlock(stamp);
}
});
executor.submit(() -> {
long stamp = lock.writeLock();
try {
System.out.println("Write Lock acquired");
ConcurrentUtils.sleep(2);
} finally {
lock.unlock(stamp);
System.out.println("Write done");
}
});
ConcurrentUtils.stop(executor);
}
}