Pourquoi attendre et notifier la fonction ne fonctionne pas correctement sur le verrou de même classe?Pourquoi attendre et notifier la fonction ne fonctionne pas correctement sur le même verrou de classe
Veuillez voir ci-dessous le code ci-dessous pour les fonctions d'attente et de notification et leur sortie.
Sortie:
Thread-1
Thread-2
Thread-2 after notify
Résultat attendu:
Thread-1
Thread-2
Thread-2 after notify
Thread-1 after wait
code:
public class WaitAndNotify1 {
public static void main(String[] args) {
Thread t1=new Thread(new Runnable(){
@Override
public void run(){
System.out.println("Thread-1");
try {
synchronized (this) {
wait();
System.out.println("Thread-1 after wait");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread t2=new Thread(new Runnable(){
@Override
public void run(){
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread-2");
synchronized (this) {
notify();
System.out.println("Thread-2 after notify");
}
}
});
t1.start();
t2.start();
}
}
Il serait vraiment utile si vous pouvez formater votre code correctement à l'avenir. .. –