Good morning,
I'm having a problem with a project involving Threads, I'm starting to mess with Threads now in a college job and I'm having doubts about Thread being in WAINTING state but not waking up even with the call from a "notifyAll", I would like to know what I am 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 the Thread can not access the required resources (forks), it goes into wait, and when another Thread "loosens" the forks, it calls the notifyAll to wake the Threads that were competing for the fork and they went into Wait, ja printei in the terminal several times the state and whenever one of the threads enters Wait it does not leave anymore. Thanks for your help and attention right away.