Witam.
Mam mały problem odnośnie wielowątkowości w Javie. Mam zrobić program typu Konsument Producent.
W programie chodzi o to, że Producent produkuje kule o losowym kolorze i dodaje do stosu. Jeśli stos będzie miał 20 kul to muszą zostać usunięte połowa z nich. Natomiast Konsument wybiera losowo kule.
Na razie zrobiłem sekcję dla Producenta i natknąłem na problem gdy chcę wywołać metodę signalAll().
Tutaj mam metodę która dodaje kule
public void add(Color c) throws InterruptedException
{
locker.lock();
try {
while(balls.size() >= BallPanel.MAX_BALLS) {
this.remove(); //Tutaj pojawia się problem.!!!!
condition.await();
}
System.out.println("Dodawanie");
int x = balls.size()*Ball.width;
Ball b = new Ball(x, c);
balls.add(b);
} finally {
locker.unlock();
}
}
A tutaj metoda która usuwa te kule
public void remove()
{
locker.lock();
try {
System.out.println("Usuwanie pilek");
try {
for(int i=(int)(balls.size()/2); i>0; i--) {
int rand = (int)(Math.random()*(BallPanel.MAX_BALLS-1));
if(balls.size() <= rand) {
i++;
} else {
System.out.println("Pilka: "+rand);
balls.remove(rand);
this.paint(this.getGraphics());
Thread.sleep((int)(Math.random()*700));
}
}
System.out.println("Pilki usuniete: "+balls.size());
condition.signalAll(); //Nie działa w tym miejscu.
} catch(InterruptedException e) {}
} finally {
locker.unlock();
}
}