¿Cuál es la diferencia entre wait() y sleep() en Java? ¿Cuándo usar cada uno?
¡Hola a todos! Acabo de empezar a entender el multithreading en Java y me confundí con dos métodos: wait() y sleep(). Ambos como que "pausan" el thread, pero se comportan de manera diferente, y no entiendo cuándo usar cada uno.
Aquí hay un ejemplo que escribí. Quiero que un thread imprima números y el segundo letras, alternándose. Pero me sale un desorden:
public class Test {
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
System.out.println(i);
try { Thread.sleep(1000); } catch (InterruptedException e) {}
}
});
Thread t2 = new Thread(() -> {
for (char c = 'A'; c < 'F'; c++) {
System.out.println(c);
try { Thread.sleep(1000); } catch (InterruptedException e) {}
}
});
t1.start();
t2.start();
}
}