0

在spring 容器环境下,通过synchronized(this)锁来执行耗时逻辑,这样能保证程序可用吗?
我测试下来如果没有返回值是能保证顺序, 有返回值就有问题.
:加synchronized 的原因是可能会并发去访问lockUserVouchers修改数据状态,修改成功或失败返回状态

clipboard.png

@Test
public void testLock() throws InterruptedException {
    CountDownLatch latch = new CountDownLatch(3);
    for (int i = 1; i <= 3; i++) {
        new Thread(new RunnerLock(userVouchersService, latch)).start();
    }
    latch.await();
}

public class RunnerLock implements Runnable {
    UserVouchersService userVouchersService;

    CountDownLatch countDownLatch;

    public RunnerLock(UserVouchersService userVouchersService, CountDownLatch     countDownLatch) {
        this.userVouchersService = userVouchersService;
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
        CsAuctionUserVouchers csAuctionUserVouchers = new CsAuctionUserVouchers();
        csAuctionUserVouchers.setId(ThreadLocalRandom.current().nextLong(0, 9999));
        long l = userVouchersService.lockUserVouchers(csAuctionUserVouchers);
        log.info("---------------返回值 --- {}---------------------------------", l);
        countDownLatch.countDown();
    }
}

    @Transactional(rollbackFor = Exception.class)
    public long lockUserVouchers(CsAuctionUserVouchers csAuctionUserVouchers) {
        synchronized (this) {
            log.info("-------------------test开始----------------------");
            try {
                Thread.sleep(1000);
                //修改数据状态,修改成功或失败返回状态
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.info("------------------ --test结束----------------------");
            return csAuctionUserVouchers.getId();
        }
    }

2018-12-07 提问
1 个回答
0

哪里有问题?

撰写答案

你可能感兴趣的

推广链接