How can I make thread 1 when it reaches 10 or more, go to thread 2 and when it finishes adding its 5 numbers it will return to thread 1 to continue its series in case it has not finished yet?
THREADS
package pruebahilos;
public class Hilos extends Thread {
Monitor mon = null;
public Hilos(String name, Monitor m) {
super(name);
mon = m;
}
@Override
public void run() {
mon.lanzar(getName());
}
Thread Hilo2 = new Thread("Hilo 2") {
@Override
public void run() {
mon.lanzar2(getName());
}
};
}
MONITOR
package pruebahilos;
public class Monitor {
public int sum = 0;
public synchronized void lanzar(String hilo1) {
try {
for (int i = 0; i < 5; i++) {
if (sum == 10) {
System.out.println("La suma dio como resultado 10");
}
int num = (int) (Math.random() * 10 + 1);
System.out.println(hilo1 + " " + " Valor " + (i + 1) + " Numero: " + num);
this.sum = this.sum + num;
System.out.println("Resultado: " + this.sum);
}
System.out.println("La suma de los numeros es: " + sum + "\n\n");
} catch (Exception e) {
System.out.println("Error en el hilo 1");
}
}
public synchronized void lanzar2(String hilo2) {
try {
if (sum <= 10) {
wait();
} else {
int res = 0;
for (int i = 0; i < 5; i++) {
if (res == 10) {
System.out.println("El Hilo 2 sumo 10 primero.");
}
int num = (int) (Math.random() * 10 + 1);
System.out.println(hilo2 + " " + " Valor " + (i + 1) + " Numero: " + num);
res = res + num;
System.out.println("Resultado: " + res);
}
System.out.println("La suma de los numeros es: " + res);
}
} catch (InterruptedException InterruptedException) {
System.out.println("Error en el hilo 2");
}
}
}
TRIAL THREAD
package pruebahilos;
public class PruebaHilos {
public static void main(String[] args) {
Monitor mon = new Monitor();
Hilos h1 = new Hilos("Hilo 1", mon);
Hilos h2 = new Hilos(" ", mon);
h1.start();
h2.Hilo2.start();
}
}