Java教程

java8之非重入锁StampedLock ,并发的另一种处理方式

本文主要是介绍java8之非重入锁StampedLock ,并发的另一种处理方式,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
package com.example.demo.config;

import java.util.concurrent.locks.StampedLock;

public class T {

    private double x, y;
    private final StampedLock sl = new StampedLock();

    // an exclusively locked method   独占锁   写互斥
    void move(double deltaX, double deltaY) {
        long stamp = sl.writeLock();
        try {
            x += deltaX;
            y += deltaY;
        } finally {
            sl.unlockWrite(stamp);
        }
    }

    double distanceFromOrigin() { // A read-only method    只读锁
        long stamp = sl.tryOptimisticRead();//返回验证的标记 是占有锁则返回0
        double currentX = x, currentY = y;

//        是占有锁sl.validate(stamp) 返回false,说明发生锁的变化则需要重新获取 重新读取
        if (!sl.validate(stamp)) {
            stamp = sl.readLock();
            try {
                currentX = x;
                currentY = y;
            } finally {
                sl.unlockRead(stamp);
            }
        }
        return Math.sqrt(currentX * currentX + currentY * currentY);
    }
       //升级可以改为以乐观而非读取模式开始
 /**
54              * 转换当前读戳为写戳,即上写锁
55              * 1.写锁戳,直接返回写锁戳
56              * 2.读锁戳且写锁可获得,则释放读锁,返回写锁戳
57              * 3.乐观读戳,当立即可用时返回写锁戳
58              * 4.其他情况返回0
59              */
void moveIfAtOrigin(double newX, double newY) { // upgrade Could instead start with optimistic, not read mode long stamp = sl.readLock(); try { while (x == 0.0 && y == 0.0) { long ws = sl.tryConvertToWriteLock(stamp); if (ws != 0L) { stamp = ws; x = newX; y = newY; break; } else { sl.unlockRead(stamp); stamp = sl.writeLock(); } } } finally { sl.unlock(stamp); } } }

 

这篇关于java8之非重入锁StampedLock ,并发的另一种处理方式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!