10000个线程更新同一行数据


@Test
public void threadTestOrderBy() throws InterruptedException {

final Long id=141284830240768L;
int threadCount=1000;
final CountDownLatch begin = new CountDownLatch(1);
final CountDownLatch end = new CountDownLatch(threadCount);
final int[] result={0,0};
final Object lock = new Object();
ExecutorService executorService = Executors.newFixedThreadPool(1000);

for (int i = 0; i < threadCount; i++) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
begin.await();
baseSiteService.updateOrderBy(id);
synchronized(lock){
result[0]++;
}
} catch (Exception ex) {
synchronized(lock) {
result[1]++;
}
ex.printStackTrace();
}finally{
end.countDown();
}
}
});
executorService.submit(thread);
}
System.out.println("1000个线程开始");
begin.countDown();
end.await();
System.out.println("1000个线程更新结束");
System.out.println("成功"+result[0]+",失败"+result[1]);
BaseSiteEntity byId = this.baseSiteService.getById(id);
System.out.println(byId.getOrderBy());
}
 

@Override
@Transactional
public void updateOrderBy(Long id) {
BaseSiteEntity byId = this.baseSiteDao.getById(id);
if (byId.getOrderBy() >= 1) {
this.baseSiteDao.updateOrderBy(id);
} else {
throw new BusinessException("没有库存");
}
}

<update id="updateOrderBy">
        update t_base_site t set t.order_by=t.order_by-1 where t.site_id=#{id}
    </update>
</mapper>
update t_base_site t set t.order_by=1 where t.site_id='141284830240768';

  条件后期不成立,但是已经开始排队更新,导致结果为-数

原文地址:https://www.cnblogs.com/zfzf1/p/7768211.html