Avatar ·

What is the difference between wait() and sleep() methods in Java? Code examples

Hi everyone! I started learning multithreading in Java and got confused about the wait() and sleep() methods. They both seem to pause thread execution, but behave differently. Help me understand. I have a simple example. I create two threads: one produces data, the other consumes it. I use sleep() for synchronization: ```java class Producer extends Thread { private List buffer = new ArrayList<>(); public void run() { for (int i = 0; i < 10; i++) { buffer.add(i); System.out.println("Produced: " + i); try { Thread.sleep(100); // Wait for consumer to take it } catch (InterruptedException e) {} } } public int getValue() { return buffer.remove(0); } ```