StampedLock如何使用?

  • StampedLock 是从 JDK1.8 开始提供,它的性能比 ReadWriteLock 好
  • StampedLock 支持:乐观读锁、悲观读锁、写锁
  • StampedLock 的悲观读锁、写锁,与 ReadWriteLock 的读锁、写锁用法相似:读读可并行、读写互斥、写写互斥。
  • StampedLock 之所以性能优于 ReadWriteLock,因为它支持乐观读锁。乐观读锁操作,支持一个线程并发进行写操作。
  • StampedLock 不支持重入
  • StampedLock 支持锁的降级和升级
  • StampedLock 可以用悲观读锁调用 readLockInterruptibly() 方法和写锁调用 writeLockInterruptibly() 方法,支持可中断

 

使用示例:

package constxiong.interview;

import java.util.Random;
import java.util.concurrent.locks.StampedLock;

/**
 * 测试 StampedLock
 * @author ConstXiong
 */
public class TestStampedLock {

    private static final StampedLock sl = new StampedLock();
    
    private static volatile int count = 0;
    
    private static final Random r = new Random();
    
    public static void main(String[] args) {
        //启动 5个线程写计数,95 个线程读计数,
        for (int i = 0; i < 100; i++) {
            if (i % 20 == 0) {
                new Thread(() -> {
                    try {
                        Thread.sleep(r.nextInt(10));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + " 计数新增 1 :" + add());
                }).start();
            } else {
                new Thread(() -> {
                    try {
                        Thread.sleep(r.nextInt(10));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + " 读计数:" + read());
                }).start();
            }    
        }
    }
    
    /**
     * 读取计数
     * @return
     */
    private static int read() {
        int r;
        long stamp = sl.tryOptimisticRead();
        r = count;
        if (!sl.validate(stamp)) {
            stamp = sl.readLock();
            try {
                r = count;
            } finally {
                sl.unlockRead(stamp);
            }
        }
        return r; 
    }
    
    /**
     * 计数加 1
     */
    private static int add() {
        long stamp = sl.writeLock();
        try {
            count++;
        } finally {
            sl.unlockWrite(stamp);
        }
        return count;
    }
    
}

 


原文链接
 


 

 

posted @ 2019-12-24 09:04  ConstXiong  阅读(514)  评论(0编辑  收藏  举报