Wait and Notify Example in Java
On this page (8sections)
Introduction
Wait And Notify is a classic Java console program that demonstrates the concept with complete source code and sample output. Threads allow concurrent execution — useful for background tasks and parallel work.
This tutorial walks through the program line by line, explains how the logic works, and highlights best practices you can apply in your own code.
Wait And Notify Example Program
public class WaitAndNotifyDemo {
public static void main(String[] args){
ThreadOne obj = new ThreadOne();
obj.start();
synchronized(obj){
try{
System.out.println("Waiting...");
obj.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("Total is: " + obj.total);
}
}
}
class ThreadOne extends Thread{
int total;
@Override
public void run(){
synchronized(this){
for(int i=0; i<10 ; i++){
total += i;
}
notify();
}
}
}
Sample Output
Waiting for obj to complete...
Total is: 45
When to use
Use this wait and notify example when learning or revising core Java syntax.
How it works
-
Execution begins in the
mainmethod — the JVM calls this method when you run the class. -
ThreadOne obj = new ThreadOne();updates a variable used in the calculation or output. -
A
println/printcall writes text to the console — part of the sample output below. -
A
println/printcall writes text to the console — part of the sample output below. -
A loop repeats the block until its condition becomes false.
-
total += i;updates a variable used in the calculation or output. -
Compare your console output with the sample output for Wait And Notify to confirm the program behaves correctly.
Best Practices
- Use meaningful variable and class names that describe their purpose.
- Compile and run the program locally — modify values to see how output changes.
- Read compiler errors carefully; they usually point to the exact line to fix.
Common Mistakes
- Copying code without understanding each line — practice by changing one statement at a time.
- Mismatching the public class name and the
.javafilename. - Forgetting semicolons at the end of statements.