Voglio eseguire due thread uno dopo l'altro, senza usare sleep() o Locks, ma si verifica un deadlock! Cosa c'è che non va nel mio codice? Ho usato wait() e notifyAll() e un oggetto Object.Java wait and notify fa deadlock
public class Test {
public static void main(String[] args) throws InterruptedException {
PrintChar a = new PrintChar('a');
PrintChar b = new PrintChar('b');
Thread ta = new Thread(a);
Thread tb = new Thread(b);
ta.start();
tb.start();
}
}
class PrintChar implements Runnable {
final Object o = new Object();
char ch;
public PrintChar(char a) {
ch = a;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
synchronized (o) {
System.out.print(ch);
try {
o.wait();
o.notifyAll();
} catch (InterruptedException ex) {
}
}
}
}
}
ho mai capito queste domande. Se vuoi l'esecuzione sequenziale, perché stai usando i thread? – EJP
Non importa, EJP! Praticando! – John