What is the difference between wait() and sleep() in Java? When to use which?
Hello everyone! I've just started learning about multithreading in Java and got confused about two methods: wait() and sleep(). Both seem to "pause" a thread, but they behave differently, and I don't understand when to use which.
Here's an example I wrote. I want one thread to output numbers and the second to output letters, alternating. But I'm getting a mess:
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++) { No answers yet.
Log in to leave an answer