What is the best practice to avoid thread conflicting? For example lets say I have this:


Code:
ArrayList arraylist;

Thread1()
{



while(true)
{
usleep(1);
if(arraylist.Size()<0)continue;

DoStuff(&arraylist);

}


}

Thread2()
{

while(something)
{
usleep(1)
arraylist.Add(stuff);
}


}

Thread3()
{

while(true)
{
RandomlyEmpty(&arraylist);
}

}

Ok so basically thread1 does some stuff to arraylist, we'll say it pops values out and reads them, when its empty, it just waits.

Thread2 puts data in arraylist. So these two threads should work well together, BUT what happens if in thread2 when the size evaluates to 1 but at that exact same time, before it does processing, thread3() empties it. Now the DoStuff(&arraylist); will have an empty array list, and we don't want that (lets just say it would crash the program).

Is there a way to prevent this? Or is this a non issue? I'm guessing theres no real set order to how many lines are run before it goes to the next thread, and so on.


So whats the best practice to handle this situation? I hope I'm making sense.