Thread in eternal Wait state, does not wake up with the notify

Asked

Viewed 57 times

2

Good morning,

I’m having a problem in a project involving Threads, I’m starting to mess with Threads right now in a college job and I’m having doubts about Thread being in the state of "WAINTING" but not waking up even with the call of a "notifyAll"I’d like to know what I’m doing wrong and the solution. Code:

public void run()
{
    try
    {
        while(true)
        {
            Thread.sleep(5000);
            if(estado == Estados.FAMINTO)
            {
                if(pegarGarfos())
                {
                    estado = Estados.COMENDO;
                }
            }
            else if(estado == Estados.PENSANDO) 
            {
                Random gerador = new Random();
                int aleatorio = gerador.nextInt()%2;
                if(aleatorio == 0)
                {
                    estado = Estados.FAMINTO;
                }
            }
            else if(estado == Estados.COMENDO)
            {
                soltarGarfos();
                estado = Estados.PENSANDO;
            }
        }

    }catch(InterruptedException ex)
    {
        System.out.println("Erro: " + ex.getMessage());
    }

}

public synchronized boolean pegarGarfos()
{
    if(!deadlock)
    {
        return garfoDireito.pegarGarfo() && garfoEsquerdo.pegarGarfo();
    }
    else
    {
        try
        {
            if(garfoDireito.pegarGarfo())
            {
                if(garfoEsquerdo.pegarGarfo())
                {
                    return true;
                }
                else
                {
                    garfoDireito.soltarGarfo();
                    this.wait();
                }
            }
            else
            {
                this.wait();
            }
        }catch(InterruptedException ex)
        {
            System.out.println("Erro: " + ex.getMessage());
        }
        return false;
    }
}

public synchronized void soltarGarfos()
{
    garfoDireito.soltarGarfo();
    garfoEsquerdo.soltarGarfo();
    this.notifyAll();
}

When Thread is unable to access the required resources (forks), she enters Wait, and when another Thread "drops" the forks she calls notifyAll to wake up the Threads that were competing for the fork and entered Wait, I have already printed in the terminal several times the state and whenever one of the Threads enters Wait it never leaves. Thank you for your help and attention.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.