本文共 1457 字,大约阅读时间需要 4 分钟。
StampedLock作为JAVA8中出现的新型锁,很可能在大多数场景都可以替代ReentrantReadWriteLock。它对于读/写都提供了四个接口(换成write为写锁):
这几个方法对应的语义为:
01 | public class TestStampedLock { |
02 | public static void main(String[] args) throws InterruptedException{ |
03 | final StampedLock lock = new StampedLock(); |
04 | new Thread(){ |
05 | public void run(){ |
06 | long readLong = lock.writeLock(); |
07 | LockSupport.parkNanos(6100000000L); |
08 | lock.unlockWrite(readLong); |
09 | } |
10 | }.start(); |
11 | Thread.sleep( 100 ); |
12 | for ( int i = 0 ; i < 3 ; ++i) |
13 | new Thread( new OccupiedCPUReadThread(lock)).start(); |
14 | } |
15 | private static class OccupiedCPUReadThread implements Runnable{ |
16 | private StampedLock lock; |
17 | public OccupiedCPUReadThread(StampedLock lock){ |
18 | this .lock = lock; |
19 | } |
20 | public void run(){ |
21 | Thread.currentThread().interrupt(); |
22 | long lockr = lock.readLock(); |
23 | System.out.println(Thread.currentThread().getName() + " get read lock" ); |
24 | lock.unlockRead(lockr); |
25 | } |
26 | } |
27 | } |
1 | boolean interrupted = false ; |
1 | if (interrupted) |
2 | Thread.currentThread().interrupt(); |
3 | return ns; |
1 | if (Thread.interrupted()){ |
2 | if (interruptible) |
3 | return cancelWaiter(node, p, true ); |
4 | else |
5 | interrupted = true ; |
6 | } |