线程并发问题 [英] Thread - concurrency issue
问题描述
例如。 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屋!