欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

深入理解Java中Lock和tryLock方法的工作原理与应用

最编程 2024-07-28 19:47:06
...

Lock接口还提供了另一种方法来获取锁,即tryLock()方法。跟lock()方法最大的不同是:线程使用tryLock()不能获取锁,tryLock()会立即返回,它不会将线程置入休眠。tryLock()方法返回一个布尔值,true表示线程获取了锁,false表示没有获取锁。

 ReentrantLock类也允许使用递归调用。如果一个线程获取了锁并且进行了递归调用,它将继续持有这个锁,因此调用lock()方法后也立即返回,并且线程将继续执行递归调用。
 

      OrderService orderService = (OrderService) AopContext.currentProxy();
            return lockComponent.tryLock(lockKey, s -> {
                try {
                    return orderService.createOrderA(orderVo, finalPrice, finalRealPrice, user, order, treasureId, finalModel, orderNumber,
                            finalAliasName, finalProduct, finalProductInfo, finalColorClassification, finalPMenuLevel, userAddress);
                } catch (BusinessException e) {
                    return JsonResult.error(e.getMessage());
                }
            });
    @Transactional(rollbackFor = Exception.class)
    @Override
    public JsonResult createOrderA(OrderVo orderVo, BigDecimal price, BigDecimal realPrice, User user, Order order, Long treasureId,
                                   String model, String orderNumber, String aliasName, Product product, ProductInfo productInfo,
                                   ColorClassification colorClassification, Long pMenuLevel, UserAddress userAddress) throws BusinessException {

//这里填写您的逻辑


}

推荐阅读