线程并发问题 [英] Thread - concurrency issue

查看:155
本文介绍了线程并发问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

带有计数列的表格。它有主键rowID。现在我想获取这个计数,将它增加1并更新它。我有一个场景,其中多个实例/线程尝试更新相同的列数。



例如。 3个线程t1,t2,t3(不同步)。 t1提取计数(比如0)并增加和更新。现在计数为1.现在有可能t2和t3可能会尝试同时访问计数,然后出现问题。

请建议正确的方法来处理这种情况。

解决方案

这是数据库序列/锁的用途。你应该使用它们。
然而,如果你想使用线程同步,你已经把'获取更新代码'放在一个同步的块或方法中。



这两种方法中的任何一种都可以达到您的目的。

 同步void method(){

// fetch
//增量
//更新

}

void method( ){

synchronized(obj){

// fetch
//增量
//更新

}

}


Table with column "count". It has primary key "rowID". Now I want to fetch this count, increment it by 1 and update it. I have a scenario where multiple instances / threads try to update the same column - count.

For eg. 3 threads t1,t2,t3 (not synchronised). t1 fetches count(say 0) and increments and updates. Now count would be 1. Now there is a chance that t2 and t3 might try to access the count simultaneously and then issues arise.

Please suggest right way to handle this scenario.

解决方案

This is what database sequences/locks are for. You should use them. However, if you want to use thread synchronization, you have put the 'fetch to update code' in a single synchronized block or method.

Either of the two methods will serve your purpose.

synchronized void method(){

        // fetch
        // increment
        // update

    }

    void method(){

        synchronized (obj) {

            // fetch
            // increment
            // update

        }

    }

这篇关于线程并发问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆