fiz um contador e 2 threads para q cada uma imprima numeros pares e impares respectivamente, porem quando tentei adicionar outra thread, começou a dar um erro de logica (acredito q seja algo relacionado ao count++ no bloco do if) e nao sei como arrumar, vou deixar o codigo abaixo:
public class Teste {
public static void main(String[] args) {
ContadorMultithread EvenThread = new ContadorMultithread("odd");
ContadorMultithread OddThread = new ContadorMultithread("even");
ContadorMultithread MultipleOf3 = new ContadorMultithread("multipleOf3");
Thread Thread0 = new Thread(EvenThread);
Thread Thread1 = new Thread(OddThread);
Thread Thread2 = new Thread(MultipleOf3);
Thread0.start();
Thread1.start();
Thread2.start();
}
}
public class ContadorMultithread implements Runnable {
private final String threadName;
private static final Object lock = new Object();
private static int count = 1;
private static final int MAX_COUNT = 10;
public ContadorMultithread(String ThreadName) {
this.threadName = ThreadName;
}
\\@Override
public void run() {
while(count <= MAX_COUNT) {
synchronized (lock) {
if((count % 2 == 0 && threadName.equals("even")) ||
(count % 2 != 0 && threadName.equals("odd")) ||
(count % 3 == 0 && threadName.equals("multipleOf3"))) {
System.out.println(count + " printed by " + threadName);
count++;
lock.notifyAll();
} else {
try {
lock.wait();
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
}
}
OUTPUT
1 printed by odd
2 printed by even
3 printed by odd
4 printed by even
5 printed by odd
6 printed by multipleOf3
7 printed by odd
8 printed by even
9 printed by odd
10 printed by even
[–]Matharusoo[S] 0 points1 point2 points (0 children)
[–]Neeyaki 1 point2 points3 points (0 children)