Teachnique
      CourseRoadmaps
      Login

      OverviewHistoryFeaturesJava 8 - New Featuresvs C++Virtual Machine(JVM)JDK vs JRE vs JVMHello World ProgramEnvironment SetupBasic SyntaxVariable TypesData TypesType CastingUnicode SystemBasic OperatorsCommentsStreamsNew Date-Time API

      Loop ControlDecision Makingif-else Statementswitch statementfor loopfor each Loopwhile Loopdo...while Loopbreak Statementcontinue Statement

      OOPs (Object-Oriented Programming) ConceptsObject and ClassesClass AttributesClass MethodsMethodsVariable ScopesConstructorsAccess ModifiersInheritanceAggregationPolymorphismOverridingMethod OverloadingDynamic BindingStatic BindingInstance Initializer BlockAbstractionEncapsulationInterfacesPackagesInner classesStatic ClassesAnonymous ClassesSingleton ClassWrapper ClassesEnum Class

      Number ClassBoolean classCharacter ClassArraysMath Class

      File ClassCreating FilesWrite To FilesReading FileDelete FilesDirectory OperationsFiles and I/O

      ExceptionsTry Catch BlockTry with ResourcesMultiple Catch BlocksNested Try BlockFinally BlockThrows and Throw | Throw an ExceptionException PropagationBuilt-in ExceptionsCustom Exception

      MultithreadingThread Life CycleCreating a ThreadStarting a ThreadJoining ThreadsNaming a Thread with ExamplesScheduling Threads with ExamplesThread PoolsMain ThreadThread PriorityDaemon ThreadThreadGroup ClassJVM Shutdown Hook

      Thread SynchronizationBlock SynchronizationStatic SynchronizationInter Thread CommunicationThread DeadlockInterrupting ThreadThread ControlReentrant Monitor

      NetworkingSocket ProgrammingURL ProcessingURL ClassURLConnection ClassHttpURLConnection ClassSocket Class with ExamplesGenerics

      Collections FrameworkCollection Interface

      List InterfaceArrayList Class

      Queue InterfaceArrayDeque Class

      Map InterfaceSortedMap Interface

      Set InterfaceSortedSet Interface

      Data Structures Enumeration Interface BitSet Class

      How to Use Iterator?How to Use Comparator?How to Use Comparable?

      RecursionRegular ExpressionsSerializationString ClassJava Arrays - Class

      Feedback

      Submit request if you have any questions.

      Course
      Inter Thread Communication

      Java Tutorial

      This Java tutorial is tailored for newcomers, offering a journey from basic principles to complex Java programming techniques. Completing this tutorial equips you with a solid understanding of Java, preparing you for advanced learning. You'll emerge ready to tackle the challenges of becoming a top-tier software engineer, with the skills to innovate and excel in the vast world of software development.

      Inter Thread Communication

      
      If you are aware of interprocess communication then it will be easy for you to understand interthread communication.

      Inter-thread Communication in Java

      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 of Inter-thread Communication in Java

      This examples shows how two threads can communicate using wait() and notify() method. You can create a complex system using the same concept.
      class Chat {
      boolean flag = false;
      
      public synchronized void Question(String msg) {
      if (flag) {
      try {
      wait();
      } catch (InterruptedException e) {
      e.printStackTrace();
      }
      }
      System.out.println(msg);
      flag = true;
      notify();
      }
      
      public synchronized void Answer(String msg) {
      if (!flag) {
      try {
      wait();
      } catch (InterruptedException e) {
      e.printStackTrace();
      }
      }
      
      System.out.println(msg);
      flag = false;
      notify();
      }
      }
      
      class T1 implements Runnable {
      Chat m;
      String[] s1 = { "Hi", "How are you ?", "I am also doing fine!" };
      
      public T1(Chat m1) {
      this.m = m1;
      new Thread(this, "Question").start();
      }
      
      public void run() {
      for (int i = 0; i < s1.length; i++) {
      m.Question(s1[i]);
      }
      }
      }
      
      class T2 implements Runnable {
      Chat m;
      String[] s2 = { "Hi", "I am good, what about you?", "Great!" };
      
      public T2(Chat m2) {
      this.m = m2;
      new Thread(this, "Answer").start();
      }
      
      public void run() {
      for (int i = 0; i < s2.length; i++) {
      m.Answer(s2[i]);
      }
      }
      }
      public class TestThread {
      public static void main(String[] args) {
      Chat m = new Chat();
      new T1(m);
      new T2(m);
      }
      }
      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!