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:
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
AtomicIntegeris wrong, because there is no locking or other concurrency control linking theincrementAndGetand theset, 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).