Ruan:
Estoy intentando ejecutar n hilos al mismo tiempo. Cada hilo debe resumir diferente matriz y actualizar el valor global.
Por desgracia, el valor mundial se actualiza de forma incorrecta.
No quiero utilizar Thread.Join ().
Este es mi código hasta ahora:
public class myClass {
private static class Values {
private static double sum;
public synchronized static void add(double dd) {
sum += dd;
};
public synchronized double get() {
return sum;
}
}
public static double CreateThreads(double[] array) {
final Values values = new Values();
...
...
...
Thread[] threads = new Thread[nOP];
for (int i = 0; i<threads.length; i++) {
threads[i] = new Thread(new Runnable() {
public void run() {
Values.add(sum(tab));
}
});
threads[i].start();
}
return values.get();
}
public static void main(String[] args) throws IOException {
double[] arr = createArray(4);
double sumLogg = CreateThreads(arr);
System.out.println("\n\nSum: " + sumLogg);
}
¿Algunas ideas?
Evgeniy Dorofeev:
Si no desea utilizar Thread.join puede utilizar CountDountLatch:
CountDownLatch cdl = new CountDownLatch(nOP);
Thread[] threads = new Thread[nOP];
for (int i = 0; i<threads.length; i++) {
threads[i] = new Thread(new Runnable() {
public void run() {
values.add(sum(tab));
cdl.countDown();
}
});
threads[i].start();
}
cdl.await();
En este caso usted no necesita utilizar la sincronización adicional, CountDownLatch es un synchronzier (ver descripción del paquete java.util.concurrent) y según su javadoc "Hasta los confines de recuento cero, las acciones en un hilo antes de llamar a Cuenta atrás () pasará antes acciones después de un exitoso regreso de un await correspondiente () en otro hilo ".