问题
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.
回答1:
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
}
}
来源:https://stackoverflow.com/questions/25743950/thread-concurrency-issue