tengo las siguientes clases en Javabucle de sincronización estancamiento
public class Counter {
private int value;
public Counter(int value) {
this.value = value;
}
public void setValue(int value) {
this.value = value;
}
public void decrement() {
this.value--;
}
public int getValue() {
return this.value;
}
}
public class Cell extends Thread {
private Object sync;
private Counter counter;
public Cell(Object sync, Counter counter) {
this.sync = sync;
this.counter = counter;
}
public void run() {
for (int r=0; r<Simulation.ROUND_NUM; r++) {
// do something
synchronized(counter) {
counter.decrement();
counter.notifyAll();
}
synchronized(sync) {
try {
sync.wait();
}
catch (Exception ex) {}
}
}
}
}
public class Simulation extends Thread {
public static final int THREAD_NUM = 5;
public static final int ROUND_NUM = 5;
public Object sync = new Object();
private Counter counter = new Counter(THREAD_NUM);
public void run() {
for (int i=0; i<THREAD_NUM; i++) {
Cell c = new Cell(sync,counter);
c.start();
}
for (int i=0; i<ROUND_NUM; i++) {
synchronized(counter) {
while(counter.getValue() != 0) {
try {
counter.wait();
}
catch (Exception ex) {}
}
counter.setValue(THREAD_NUM);
}
synchronized(sync) {
sync.notifyAll();
}
}
}
}
El objetivo es evitar que se ejecute la siguiente iteración del bucle en cada hilo de la célula, hasta que cada hilo de la célula se llevará a cabo en cada iteración. Mi solución a veces conduce a un punto muerto. No puedo entender por qué. Por favor, ayuda
Nota al margen: si no necesita explícitamente utilizar 'Thread',' wait' y 'notify' (y está utilizando Java5 o posterior), sería mejor que tuviera un [' CountDownLatch'] (http : //download.oracle.com/javase/6/docs/api/java/util/concurrent/CountDownLatch.html) en su lugar. –