SlideShare una empresa de Scribd logo
1 de 22
Inter thread Communication




                             1
Objectives


On completion of this period, you would be
able to learn

•   Inter thread communication methods
•   wait() method
•   notify() method
•   Producer-Consumer problem
•   Solution to Producer-Consumer problem




                                             2
Recap

In the previous class, you have learnt

•   Synchronization
•   Monitor
•   Unsynchronized examples
•   Locking objects
•   Examples on synchronization




                                         3
Inter Thread Communication Methods
• When more than one thread uses a shared
  resource they need to synchronize with each other

• While using a shared resource the threads need
  to communicate with each other, to get the
  expected behavior of the application

• Java provides some methods for the threads to
  communicate


                                                      4
Inter Thread Communication Methods
                       Contd..




      Table 38.1. Inter Thread Communication Methods




                                                       5
wait() Method

• wait() method causes a thread to release the lock
  it is holding on an object; allowing another thread
  to run
• wait() method is defined in the Object class
• wait() can only be invoked from within
  synchronized code
• It should always be wrapped in a try block as it
  throws IOExceptions
• wait() can only invoked by the thread that owns
  the lock on the object
                                                        6
wait() Method
                                        Contd . . .

• When wait() is called, the thread becomes
  disabled for scheduling and lies dormant until
  one of four things occur:
  • another thread invokes the notify() method for this
    object and the scheduler arbitrarily chooses to run the
    thread
  • another thread invokes the notifyAll() method for this
    object
  • another thread interrupts this thread
  • the specified wait() time elapses



                                                              7
wait() Method
                                   Contd . . .

• When one of the above occurs, the thread
  becomes re-available to the thread scheduler and
  competes for a lock on the object

• Once it regains the lock on the object, everything
  resumes as if no suspension had occurred




                                                       8
notify() Method

• Wakes up a single thread that is waiting on
  this object's monitor
  • If any threads are waiting on this object, one of them is
    chosen to be awakened
  • The choice is arbitrary and occurs at the discretion of
    the implementation
• Can only be used within synchronized code
• The awakened thread will not be able to proceed
  until the current thread relinquishes the lock on
  this object

                                                                9
Producer-Consumer Problem

• Producing thread may write to buffer (shared
  memory)
• Consuming thread reads from buffer
• If not synchronized, data can become corrupted
  • Producer may write before consumer read last data
     • Data lost
  • Consumer may read before producer writes new data
     • Data "doubled"



                                                        10
Producer-Consumer Problem
                                           Contd . . .
• Using synchronization

  • If producer knows that consumer has not read last
    data, calls wait (awaits a notify command from
    consumer)

  • If consumer knows producer has not updated data,
    calls wait (awaits notify command from producer)




                                                         11
Incorrect Implementation
class Q {                                         public void run() {
  int n;                     class Q is treated int i = 0;
  synchronized int get() { as Buffer               while(true) {
    System.out.println("Got: " + n);                 q.put(i++);
                                                   }
    return n;
                                                 }
  }                                            }
  synchronized void put(int n) {
    this.n = n;                                class Consumer implements Runnable {
    System.out.println("Put: " + n);             Q q;
                                                 Consumer(Q q) {
  }                                                                   Consumer class
                                                   this.q = q;
}                                                  new Thread(this, "Consumer").start();
class Producer implements Runnable {             }
  Q q;                                           public void run() {
  Producer(Q q) {                                  while(true) {
                           Producer class            q.get();
    this.q = q;                                    }
    new Thread(this, "Producer").start();        }
  }                                            }
                                                                                           12
Incorrect Implementation
                                                Contd . . .
class PC {
  public static void main(String args[]) {
    Q q = new Q();
    new Producer(q);
    new Consumer(q);
    System.out.println("Press Control-C to stop.");
  }
}




                                                              13
Incorrect Implementation
                                               Contd . . .
Output




         Only Producer is doing
                                   Though producer and
         work
                                   consumer are working,
                                   there is no sync between
                                   them




                                                              14
Correct Implementation
class Q {                                          synchronized void put(int n) {
 int n;                      class Q is treated if(valueSet)
 boolean valueSet = false; as Buffer                try {
 synchronized int get() {                             wait();
                                                    } catch(InterruptedException e) {
   if(!valueSet)
                                                      System.out.println("InterruptedException
     try {                                     caught");
       wait();                                      }
             } catch(InterruptedException e)
     {     System.out.println("InterruptedExce      this.n = n;
     ption caught");                                valueSet = true;
     }                                              System.out.println("Put: " + n);
                                                    notify();
     System.out.println("Got: " + n);
                                                 }
     valueSet = false;                         }                            Use of wait and
     notify();             Use of wait and                                  notify
     return n;             notify
 }
             get() is used by Consumer and put () is used by Producer
                                                                                             15
Correct Implementation
                                                                        Contd . . .
class Producer implements Runnable {              class Consumer implements Runnable {
 Q q;                                             Q q;

    Producer(Q q) {         Producer class        Consumer(Q q) { Consumer class
                                                    this.q = q;
      this.q = q;
                                                    new Thread(this, "Consumer").start();
      new Thread(this, "Producer").start();       }
    }
                                                  public void run() {
    public void run() {                             while(true) {
                                                      q.get();
     int i = 0;
                                                    }
                                                  }
        while(true) {                         }
          q.put(i++);
        }
    }
}

                                                                                            16
Correct Implementation
                                  Contd . . .
Output




         put and get are in
         synch




                                                17
Summary

• In this class, you have learnt

   • The methods for doing inter thread communication
   • Producer-Consumer problem
   • A program that implements Producer-Consumer
     problem


• In the next lesson we look at Deadlock problem



                                                        18
Quiz

1. Which is NOT a method useful for interThread
   communication ?

  A.   wait()
  B.   notify()
  C.   suspend()
  D.   notifyAll()




                                                  19
Quiz   Contd..

2. During wait(), which method wakes up the
  thread ?

  A.   resume()
  B.   sleep()
  C.   notify()
  D.   yield()




                                              20
Frequently Asked Questions

1. Which methods are useful for inter thread
   communication ?
2. Explain the wait() method
3. Explain the notify() method
4. Define and explain Producer-Consumer
   problem




                                               21
Assignments

• Modify the Producer-Consumer program, such
  that the producer generates a prime number and
  consumer prints the square of that prime number




                                                    22

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVA
 
Java string handling
Java string handlingJava string handling
Java string handling
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
 
Basic of Multithreading in JAva
Basic of Multithreading in JAvaBasic of Multithreading in JAva
Basic of Multithreading in JAva
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Java I/O
Java I/OJava I/O
Java I/O
 
Java Streams
Java StreamsJava Streams
Java Streams
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
Applets
AppletsApplets
Applets
 
Java String
Java StringJava String
Java String
 
Inter Thread Communicationn.pptx
Inter Thread Communicationn.pptxInter Thread Communicationn.pptx
Inter Thread Communicationn.pptx
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 
Java static keyword
Java static keywordJava static keyword
Java static keyword
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Files in java
Files in javaFiles in java
Files in java
 

Destacado

Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Javaparag
 
Java util concurrent
Java util concurrentJava util concurrent
Java util concurrentRoger Xia
 
Developer Friendly API Design
Developer Friendly API DesignDeveloper Friendly API Design
Developer Friendly API Designtheamiableapi
 
Java concurrency - Thread pools
Java concurrency - Thread poolsJava concurrency - Thread pools
Java concurrency - Thread poolsmaksym220889
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in JavaTushar B Kute
 
Process Synchronization And Deadlocks
Process Synchronization And DeadlocksProcess Synchronization And Deadlocks
Process Synchronization And Deadlockstech2click
 
Java data structures for principled programmer
Java data structures for principled programmerJava data structures for principled programmer
Java data structures for principled programmerspnr15z
 
Distributed computing
Distributed computingDistributed computing
Distributed computingshivli0769
 
Java multi threading
Java multi threadingJava multi threading
Java multi threadingRaja Sekhar
 

Destacado (12)

Multi threading
Multi threadingMulti threading
Multi threading
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
 
Java util concurrent
Java util concurrentJava util concurrent
Java util concurrent
 
Developer Friendly API Design
Developer Friendly API DesignDeveloper Friendly API Design
Developer Friendly API Design
 
Networking in Java
Networking in JavaNetworking in Java
Networking in Java
 
Java concurrency - Thread pools
Java concurrency - Thread poolsJava concurrency - Thread pools
Java concurrency - Thread pools
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
 
Process Synchronization And Deadlocks
Process Synchronization And DeadlocksProcess Synchronization And Deadlocks
Process Synchronization And Deadlocks
 
Java data structures for principled programmer
Java data structures for principled programmerJava data structures for principled programmer
Java data structures for principled programmer
 
Multi tasking ppt
Multi tasking pptMulti tasking ppt
Multi tasking ppt
 
Distributed computing
Distributed computingDistributed computing
Distributed computing
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
 

Similar a Inter threadcommunication.38

Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrencypriyank09
 
31b - JUnit and Mockito.pdf
31b - JUnit and Mockito.pdf31b - JUnit and Mockito.pdf
31b - JUnit and Mockito.pdfgauravavam
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronizationpriyabogra1
 
Synchronization.37
Synchronization.37Synchronization.37
Synchronization.37myrajendra
 
Introduction to TDD with FlexUnit
Introduction to TDD with FlexUnitIntroduction to TDD with FlexUnit
Introduction to TDD with FlexUnitAnupom Syam
 
Java Programs
Java ProgramsJava Programs
Java Programsvvpadhu
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsCarol McDonald
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good TestsTomek Kaczanowski
 
Unit Testing with JUnit4 by Ravikiran Janardhana
Unit Testing with JUnit4 by Ravikiran JanardhanaUnit Testing with JUnit4 by Ravikiran Janardhana
Unit Testing with JUnit4 by Ravikiran JanardhanaRavikiran J
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and ClassesIntro C# Book
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrencyfeng lee
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good TestsTomek Kaczanowski
 
CSharp for Unity Day2
CSharp for Unity Day2CSharp for Unity Day2
CSharp for Unity Day2Duong Thanh
 
CJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxCJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxRAJASEKHARV10
 
Effective java item 80 and 81
Effective java   item 80 and 81Effective java   item 80 and 81
Effective java item 80 and 81Isaac Liao
 

Similar a Inter threadcommunication.38 (20)

04 threads
04 threads04 threads
04 threads
 
Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrency
 
31b - JUnit and Mockito.pdf
31b - JUnit and Mockito.pdf31b - JUnit and Mockito.pdf
31b - JUnit and Mockito.pdf
 
Java Week9(B) Notepad
Java Week9(B)   NotepadJava Week9(B)   Notepad
Java Week9(B) Notepad
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
 
Synchronization.37
Synchronization.37Synchronization.37
Synchronization.37
 
Introduction to TDD with FlexUnit
Introduction to TDD with FlexUnitIntroduction to TDD with FlexUnit
Introduction to TDD with FlexUnit
 
Java Programs
Java ProgramsJava Programs
Java Programs
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and Trends
 
Thread
ThreadThread
Thread
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
 
Unit Testing with JUnit4 by Ravikiran Janardhana
Unit Testing with JUnit4 by Ravikiran JanardhanaUnit Testing with JUnit4 by Ravikiran Janardhana
Unit Testing with JUnit4 by Ravikiran Janardhana
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and Classes
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrency
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
CSharp for Unity Day2
CSharp for Unity Day2CSharp for Unity Day2
CSharp for Unity Day2
 
CJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxCJP Unit-1 contd.pptx
CJP Unit-1 contd.pptx
 
Effective java item 80 and 81
Effective java   item 80 and 81Effective java   item 80 and 81
Effective java item 80 and 81
 
Test driven development
Test driven developmentTest driven development
Test driven development
 

Más de myrajendra (20)

Fundamentals
FundamentalsFundamentals
Fundamentals
 
Data type
Data typeData type
Data type
 
Hibernate example1
Hibernate example1Hibernate example1
Hibernate example1
 
Jdbc workflow
Jdbc workflowJdbc workflow
Jdbc workflow
 
2 jdbc drivers
2 jdbc drivers2 jdbc drivers
2 jdbc drivers
 
3 jdbc api
3 jdbc api3 jdbc api
3 jdbc api
 
4 jdbc step1
4 jdbc step14 jdbc step1
4 jdbc step1
 
Dao example
Dao exampleDao example
Dao example
 
Sessionex1
Sessionex1Sessionex1
Sessionex1
 
Internal
InternalInternal
Internal
 
3. elements
3. elements3. elements
3. elements
 
2. attributes
2. attributes2. attributes
2. attributes
 
1 introduction to html
1 introduction to html1 introduction to html
1 introduction to html
 
Headings
HeadingsHeadings
Headings
 
Forms
FormsForms
Forms
 
Css
CssCss
Css
 
Views
ViewsViews
Views
 
Views
ViewsViews
Views
 
Views
ViewsViews
Views
 
Starting jdbc
Starting jdbcStarting jdbc
Starting jdbc
 

Inter threadcommunication.38

  • 2. Objectives On completion of this period, you would be able to learn • Inter thread communication methods • wait() method • notify() method • Producer-Consumer problem • Solution to Producer-Consumer problem 2
  • 3. Recap In the previous class, you have learnt • Synchronization • Monitor • Unsynchronized examples • Locking objects • Examples on synchronization 3
  • 4. Inter Thread Communication Methods • When more than one thread uses a shared resource they need to synchronize with each other • While using a shared resource the threads need to communicate with each other, to get the expected behavior of the application • Java provides some methods for the threads to communicate 4
  • 5. Inter Thread Communication Methods Contd.. Table 38.1. Inter Thread Communication Methods 5
  • 6. wait() Method • wait() method causes a thread to release the lock it is holding on an object; allowing another thread to run • wait() method is defined in the Object class • wait() can only be invoked from within synchronized code • It should always be wrapped in a try block as it throws IOExceptions • wait() can only invoked by the thread that owns the lock on the object 6
  • 7. wait() Method Contd . . . • When wait() is called, the thread becomes disabled for scheduling and lies dormant until one of four things occur: • another thread invokes the notify() method for this object and the scheduler arbitrarily chooses to run the thread • another thread invokes the notifyAll() method for this object • another thread interrupts this thread • the specified wait() time elapses 7
  • 8. wait() Method Contd . . . • When one of the above occurs, the thread becomes re-available to the thread scheduler and competes for a lock on the object • Once it regains the lock on the object, everything resumes as if no suspension had occurred 8
  • 9. notify() Method • Wakes up a single thread that is waiting on this object's monitor • If any threads are waiting on this object, one of them is chosen to be awakened • The choice is arbitrary and occurs at the discretion of the implementation • Can only be used within synchronized code • The awakened thread will not be able to proceed until the current thread relinquishes the lock on this object 9
  • 10. Producer-Consumer Problem • Producing thread may write to buffer (shared memory) • Consuming thread reads from buffer • If not synchronized, data can become corrupted • Producer may write before consumer read last data • Data lost • Consumer may read before producer writes new data • Data "doubled" 10
  • 11. Producer-Consumer Problem Contd . . . • Using synchronization • If producer knows that consumer has not read last data, calls wait (awaits a notify command from consumer) • If consumer knows producer has not updated data, calls wait (awaits notify command from producer) 11
  • 12. Incorrect Implementation class Q { public void run() { int n; class Q is treated int i = 0; synchronized int get() { as Buffer while(true) { System.out.println("Got: " + n); q.put(i++); } return n; } } } synchronized void put(int n) { this.n = n; class Consumer implements Runnable { System.out.println("Put: " + n); Q q; Consumer(Q q) { } Consumer class this.q = q; } new Thread(this, "Consumer").start(); class Producer implements Runnable { } Q q; public void run() { Producer(Q q) { while(true) { Producer class q.get(); this.q = q; } new Thread(this, "Producer").start(); } } } 12
  • 13. Incorrect Implementation Contd . . . class PC { public static void main(String args[]) { Q q = new Q(); new Producer(q); new Consumer(q); System.out.println("Press Control-C to stop."); } } 13
  • 14. Incorrect Implementation Contd . . . Output Only Producer is doing Though producer and work consumer are working, there is no sync between them 14
  • 15. Correct Implementation class Q { synchronized void put(int n) { int n; class Q is treated if(valueSet) boolean valueSet = false; as Buffer try { synchronized int get() { wait(); } catch(InterruptedException e) { if(!valueSet) System.out.println("InterruptedException try { caught"); wait(); } } catch(InterruptedException e) { System.out.println("InterruptedExce this.n = n; ption caught"); valueSet = true; } System.out.println("Put: " + n); notify(); System.out.println("Got: " + n); } valueSet = false; } Use of wait and notify(); Use of wait and notify return n; notify } get() is used by Consumer and put () is used by Producer 15
  • 16. Correct Implementation Contd . . . class Producer implements Runnable { class Consumer implements Runnable { Q q; Q q; Producer(Q q) { Producer class Consumer(Q q) { Consumer class this.q = q; this.q = q; new Thread(this, "Consumer").start(); new Thread(this, "Producer").start(); } } public void run() { public void run() { while(true) { q.get(); int i = 0; } } while(true) { } q.put(i++); } } } 16
  • 17. Correct Implementation Contd . . . Output put and get are in synch 17
  • 18. Summary • In this class, you have learnt • The methods for doing inter thread communication • Producer-Consumer problem • A program that implements Producer-Consumer problem • In the next lesson we look at Deadlock problem 18
  • 19. Quiz 1. Which is NOT a method useful for interThread communication ? A. wait() B. notify() C. suspend() D. notifyAll() 19
  • 20. Quiz Contd.. 2. During wait(), which method wakes up the thread ? A. resume() B. sleep() C. notify() D. yield() 20
  • 21. Frequently Asked Questions 1. Which methods are useful for inter thread communication ? 2. Explain the wait() method 3. Explain the notify() method 4. Define and explain Producer-Consumer problem 21
  • 22. Assignments • Modify the Producer-Consumer program, such that the producer generates a prime number and consumer prints the square of that prime number 22