Java – how does atomicinteger work?

I don't think threading is such a difficult sigh

if(++threadcounter==3){doSomething(); threadcounter =0;}

I find this not a good idea because thread counters sometimes never reach 4

So I used atomic integers

if(atomicint.incrementAndGet()==4){doSomething(); atomicint.set(0);}

The counter is 5 or 0 and the application is frozen I don't know what happened How to use the correct counter? thank you

Edit:

Solution

The easiest way to solve this problem is to use a good old lock:

boolean shouldDoSomething;
synchronized {
    ++threadCounter;
    if (threadCounter == 4) {
        threadCounter = 0;
        shouldDoSomething = true;
    }
    else {
        shouldDoSomething = false;
    }
}
if (shouldDoSomething) doSomething();

This will create contention on the lock, but it will create contention in a very, very short piece of code - a load, a store, and some arithmetic instructions

Your use of atomicinteger is wrong because there is no lock or other concurrency control link incrementandget and collection, which means that there is a potential race condition (value 3, thread a is incremented to 4, thread B is incremented to 5, and thread a is set to 0)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>