Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Thread Communication



Inter-thread communication is important when you develop an application where two or more threads exchange some information. Inter-thread communication is achieved by using the wait(), notify(), and notifyAll() methods of the Object class.

Methods used for Inter-thread Communication

There are three simple methods and a little trick which makes thread communication possible. All the three methods are listed below −

Sr.No. Method & Description
1

public void wait()

Causes the current thread to wait until another thread invokes the notify().

2

public void notify()

Wakes up a single thread that is waiting on this object's monitor.

3

public void notifyAll()

Wakes up all the threads that called wait( ) on the same object.

These methods have been implemented as final methods in Object, so they are available in all the classes. All three methods can be called only from within a synchronized context.

Example - Inter-thread Communication

This examples shows how two threads can communicate using wait() and notify() method. You can create a complex system using the same concept.

Example.groovy

class Example {
   static void main(String[] args) {
      Chat chat = new Chat();
      String[] questions = [ "Hi", "How are you ?", "I am also doing fine!" ];
      String[] answers = [ "Hi", "I am good, what about you?", "Great!" ];
      new User(chat, "Question", questions, true);
      new User(chat, "Answer", answers, false);
   }
}
class Chat {
   boolean flag = false;

   synchronized void Question(String msg) {
      if (flag) {
         try {
            wait();
         } catch (InterruptedException e) {
            e.printStackTrace();
         }
      }
      println(msg);
      flag = true;
      notify();
   }

   synchronized void Answer(String msg) {
      if (!flag) {
         try {
            wait();
         } catch (InterruptedException e) {
            e.printStackTrace();
         }
      }
      println(msg);
      flag = false;
      notify();
   }
}

class User implements Runnable {
   Chat chat;
   String[] messages;
   boolean isQuestion;

   User(Chat chat, String threadName, String[] messages, boolean isQuestion) {
      this.chat = chat;
      this.messages = messages;
      this.isQuestion = isQuestion;
      new Thread(this, threadName).start();
   }

   void run() {
      if(this.isQuestion){
         for (int i = 0; i < messages.length; i++) {
            chat.Question(messages[i]);
         }	 
      } else {
         for (int i = 0; i < messages.length; i++) {
            chat.Answer(messages[i]);
         }	 
      }      
   }
}

When the above program is complied and executed, it produces the following result −

Output

Hi
Hi
How are you ?
I am good, what about you?
I am also doing fine!
Great!
Advertisements