Java - how to avoid Thread Starvation when we have lots of threads

614 views Asked by At

I would appreciate it if you could help me understand how one can approach multithreading and avoid starvation.

I have an array of the same class, for instance, class Animal, which should walk, eat, speak, etc. I have thought of using every Class Animal thread (By implementing Runnable). Still, I encountered the issue that I have to use Thread.sleep() in the while loop so that every other Animal in my array of Animals will have time to execute tasks.

My issue with the sleep approach is that I don't know how much time each thread should sleep, and it seems to be wrong to make the thread sleep when he can instead work (For example, he is the only thread running now).

My question is how can I avoid using Thread.sleep() and prevent Thread starvation when I have multiple threads of the same class.

The main loop where I check for changes in the Animals and repaint

@Override
public void run() {
    while (true) {
        repaint();
        try {
            sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        checkIfEat(); // Iterate over all animals and see if they can eat eachother
    }
}

The thread the Animal object uses

@Override
public void run() {
    Point currentLocation;
    while (true) {
        currentLocation = getLocation();
        move(currentLocation.getX() + getHorSpeed() * getX_dir(), currentLocation.getY() + getVerSpeed() * getY_dir()); // move the animal to other location

    }
}
0

There are 0 answers