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);
}
```
No answers yet.
Log in to leave an answer
Blogs
Asynchronous Programming in PHP: A Complete Guide
Caching in Go: Redis, Memcached, and Built-in Solutions
C# for Machine Learning: Capabilities, Limitations, and Examples for Beginners
Learn Python for Automation: Best Courses & Resources 2025