Differences Between wait() and join() Methods in Java



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. Key wait() join()
1 Declaration wait() 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.
2 Usage wait() 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.
3 Counter method As 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.
4 Context In 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..
5 Lock Release wait() releases the monitor or lock held on the object which wait is invoked on On 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
Updated on: 2019-09-18T14:16:47+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements