Java Multi Threading - Thread wait and notify methods
Thread - wait() and notify() methods
Whenever we execute a main method, we will have Main Thread running. In our example, we execute a new thread invoked from the main method. New Thread is doing the calculations. The main thread needs to print the result of the output of the new thread.
This requirement can be solved by
Example - Thread without using wait() and notify() methods
public class ThreadWithoutWaitAndNotifyExample extends Thread{
String threadName;
int sum;
public ThreadWithoutWaitAndNotifyExample(String name){
this.threadName=name;
}
public void run(){
System.out.println("Inside thread: " + threadName);
sum=0;
for(int i=0; i<1000;i++){
sum=sum+i;
}
}
//Main Thread
public static void main(String a[]){
ThreadWithoutWaitAndNotifyExample thread1
= new ThreadWithoutWaitAndNotifyExample("Thread1");
thread1.start();
System.out.println("sum:"+thread1.sum);
}
}
Output - Thread without using wait() and notify() method
sum:0 Inside thread: Thread1
In the above code, Main thread prints the results before the other thread (thread1) calculates the sum of numbers 1 to 1000. This is because the main thread (current thread) did not wait for the other thread to complete. In order to make the main thread (current thread) wait for thread1 to complete, we need to call thread1.wait() from within the main method().
Java Thread Example - MultiThreading with wait() and notify()
public class ThreadWaitAndNotifyExample extends Thread{
String threadName;
int sum;
public ThreadWaitAndNotifyExample(String name){
this.threadName=name;
}
public void run(){
System.out.println("Inside thread: " + threadName);
sum=0;
synchronized(this){
for(int i=0; i<1000;i++){
sum=sum+i;
}
notify();
}
}
public static void main(String a[]){
ThreadWaitAndNotifyExample thread1= new ThreadWaitAndNotifyExample("Thread1");
thread1.start();
try {
synchronized(thread1){
thread1.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("sum:"+thread1.sum);
}
}
Output - MultiThreading with wait() and notify()
Inside thread: Thread1 sum:499500