0
Inter thread Communication                             1
ObjectivesOn completion of this period, you would beable to learn•   Inter thread communication methods•   wait() method• ...
RecapIn the previous class, you have learnt•   Synchronization•   Monitor•   Unsynchronized examples•   Locking objects•  ...
Inter Thread Communication Methods• When more than one thread uses a shared  resource they need to synchronize with each o...
Inter Thread Communication Methods                       Contd..      Table 38.1. Inter Thread Communication Methods      ...
wait() Method• wait() method causes a thread to release the lock  it is holding on an object; allowing another thread  to ...
wait() Method                                        Contd . . .• When wait() is called, the thread becomes  disabled for ...
wait() Method                                   Contd . . .• When one of the above occurs, the thread  becomes re-availabl...
notify() Method• Wakes up a single thread that is waiting on  this objects monitor  • If any threads are waiting on this o...
Producer-Consumer Problem• Producing thread may write to buffer (shared  memory)• Consuming thread reads from buffer• If n...
Producer-Consumer Problem                                           Contd . . .• Using synchronization  • If producer know...
Incorrect Implementationclass Q {                                         public void run() {  int n;                     ...
Incorrect Implementation                                                Contd . . .class PC {  public static void main(Str...
Incorrect Implementation                                               Contd . . .Output         Only Producer is doing   ...
Correct Implementationclass Q {                                          synchronized void put(int n) { int n;            ...
Correct Implementation                                                                        Contd . . .class Producer im...
Correct Implementation                                  Contd . . .Output         put and get are in         synch        ...
Summary• In this class, you have learnt   • The methods for doing inter thread communication   • Producer-Consumer problem...
Quiz1. Which is NOT a method useful for interThread   communication ?  A.   wait()  B.   notify()  C.   suspend()  D.   no...
Quiz   Contd..2. During wait(), which method wakes up the  thread ?  A.   resume()  B.   sleep()  C.   notify()  D.   yiel...
Frequently Asked Questions1. Which methods are useful for inter thread   communication ?2. Explain the wait() method3. Exp...
Assignments• Modify the Producer-Consumer program, such  that the producer generates a prime number and  consumer prints t...
Upcoming SlideShare
Loading in...5
×

Inter threadcommunication.38

370

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
370
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
6
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Transcript of "Inter threadcommunication.38"

  1. 1. Inter thread Communication 1
  2. 2. ObjectivesOn completion of this period, you would beable to learn• Inter thread communication methods• wait() method• notify() method• Producer-Consumer problem• Solution to Producer-Consumer problem 2
  3. 3. RecapIn the previous class, you have learnt• Synchronization• Monitor• Unsynchronized examples• Locking objects• Examples on synchronization 3
  4. 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. 5. Inter Thread Communication Methods Contd.. Table 38.1. Inter Thread Communication Methods 5
  6. 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. 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. 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. 9. notify() Method• Wakes up a single thread that is waiting on this objects 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. 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. 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. 12. Incorrect Implementationclass 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. 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. 14. Incorrect Implementation Contd . . .Output Only Producer is doing Though producer and work consumer are working, there is no sync between them 14
  15. 15. Correct Implementationclass 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. 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. 17. Correct Implementation Contd . . .Output put and get are in synch 17
  18. 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. 19. Quiz1. Which is NOT a method useful for interThread communication ? A. wait() B. notify() C. suspend() D. notifyAll() 19
  20. 20. Quiz Contd..2. During wait(), which method wakes up the thread ? A. resume() B. sleep() C. notify() D. yield() 20
  21. 21. Frequently Asked Questions1. Which methods are useful for inter thread communication ?2. Explain the wait() method3. Explain the notify() method4. Define and explain Producer-Consumer problem 21
  22. 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
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×