Differences between wait() and join() methods in Java

Java 8Object Oriented ProgrammingProgramming

In multithreading when we deal with threads there comes the requirement of pause and start a thread for this Threading provides two methods wait and join which are used for the same.

The following are the important differences between wait() and join().

Sr. No.Keywait()join()
1Declarationwait() method is defined in Object class and hence the wait() method is declared in java.lang package.join() method, on the other hand, is also defined in java.lang package but in Thread class.
2Usagewait() method is primarily used for the inter-thread communication.On the other hand join() is used for adding sequencing between multiple threads, one thread starts execution after first thread execution finished.
3Counter methodAs wait() method is used to pause the current thread so its counter method is also provided in object class to resume the thread which is notify() and notifyAll().On the other hand we can not break the waiting imposed by join() method without unless or interruption the thread on which join is called has execution finished.
4ContextIn order to call wait method we require synchronized block or method as if wait() method is called outside the synchronized context it will throw IllegalMonitorStateException.On the other no such condition required for calling join() method and we can call join() method with and without synchronized context in Java..
5Lock Releasewait() releases the monitor or lock held on the object which wait is invoked onOn the other hand, calling join() method doesn't release any monitor or lock.

Example of wait() vs join()

JavaTester.java

 Live Demo

public class JavaTester extends Thread {
   static Object lock = new Object();
   static int n;
   int i;
   String name;
   JavaTester(String name, int i) {
      this.name = name;
      this.i = i;
   }
   @Override
   public void run() {
      try {
         synchronized (lock) {
            while (i != n) {
               lock.wait();
            }
            System.out.println(name + " started");
            n++;
            lock.notifyAll();
         }
         synchronized (lock) {
            while (i != n - 4) {
               lock.wait();
            }
            System.out.println(name + " finished");
            n++;
            lock.notifyAll();
         }
      }
      catch (InterruptedException e) {
      }
   }
   public static void main(String[] args) throws Exception {
      new JavaTester("a", 0).start();
      new JavaTester("b", 1).start();
      new JavaTester("c", 2).start();
      new JavaTester("d", 3).start();
   }
}

Output

a started
b started
c started
d started
a finished
b finished
c finished
d finished
raja
Published on 18-Sep-2019 13:57:43
Advertisements