I didn't think threading would be this difficult sigh. Anyways, the only way I could think of executing a function after a thread has completed is to use a static counter to increment whenever a thread ran.
if(++threadcounter==3){doSomething(); threadcounter =0;}
I found this wasn't a good idea because the threadcounter at times never reaches 4.
So I used atomic integer
if(atomicint.incrementAndGet()==4){doSomething(); atomicint.set(0);}
The counter is 5 or 0 and the app freezes. I don't know what's happening. How to use a correct counter? Thanks
EDIT:
The simplest way to tackle this is with a good old-fashioned 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 over a very, very brief piece of code - a load, a store, and a few arithmetic instructions.
Your use of AtomicInteger
is wrong, because there is no locking or other concurrency control linking the incrementAndGet
and the set
, which means there is a potential race condition (value is 3, thread A increments to 4, thread B increments to 5, thread A sets to 0).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With