Inter Thread Communication Inwards Coffee Using Await Notify Example

Wait as well as notify methods inwards Java are used for inter-thread communication i.e. if i thread wants to say something to or hence other thread, it uses notify() and notifyAll() method of java.lang.Object. Classical representative of hold off as well as notify method is Producer Consumer pattern pattern, where One thread create as well as seat something on shared bucket, as well as and hence say other thread that in that place is an especial for your involvement inwards shared object, consumer thread than selection than especial as well as do his job, without wait() as well as notify(), consumer thread needs to last busy checking, fifty-fifty if in that place is no modify inwards nation of shared object.

This brings an interesting betoken on using hold off as well as notify mechanism, a telephone cry upwards to notify() happens, when thread changed nation of shared object i.e. inwards this instance producer modify bucket from empty to non empty, as well as consumer modify nation from non-empty to empty.

Also wait as well as notify method must last called from synchronized context, wondering why, read this link for or hence reasons which makes sense. Another of import matter to expire on inwards withdraw heed spell calling them is, using loop to banking enterprise gibe weather instead of if block.

This is actually tricky for beginners, which frequently don't sympathise divergence as well as wonders why hold off as well as notify acquire called shape loops. Joshua Bloch has a real informative especial on his majority Effective Java, I strongly propose reading that.

In short, a waiting thread may woke up, without whatever modify inwards it's waiting status due to spurious wake up.

For example, if a consumer thread, which is waiting because shared queue is empty, gets wake upwards due to a faux alert as well as elbow grease to acquire something from queue without farther checking whether queue is empty or non than unexpected number is possible.

Here is touchstone idiom for calling wait, notify as well as notifyAll methods inwards Java :




How to telephone cry upwards hold off method inwards Java :

synchronized (object) {
         while ()
             object.wait();
         ... // Perform activity appropriate to condition
 }

as well as hither is consummate representative of calling hold off as well as notify method inwards Java using 2 threads, producer as well as consumer

 Wait as well as notify methods inwards Java are used for inter Inter Thread Communication inwards Java using Wait Notify Example


Java Inter Thread Communication Example - Wait as well as Notify

 Wait as well as notify methods inwards Java are used for inter Inter Thread Communication inwards Java using Wait Notify Exampletwo threads called Producer and Consumer. Producer thread puts number into shared queue as well as Consumer thread consumes numbers from shared bucket. Condition is that i time an especial is produced, consumer thread has to last notified as well as similarly later on consumption producer thread needs to last notified. This inter thread communication is achieved using hold off as well as notify method. Remember wait as well as notify method is defined inwards object class, as well as they are must last called within synchronized block.

package concurrency;
import java.util.LinkedList;
import java.util.Queue;
import org.apache.log4j.Logger;

public class InterThreadCommunicationExample {

    public static void main(String args[]) {

        final Queue sharedQ = new LinkedList();

        Thread producer = new Producer(sharedQ);
        Thread consumer = new Consumer(sharedQ);

        producer.start();
        consumer.start();

    }
}

public class Producer extends Thread {
    private static final Logger logger = Logger.getLogger(Producer.class);
    private final Queue sharedQ;

    public Producer(Queue sharedQ) {
        super("Producer");
        this.sharedQ = sharedQ;
    }

    @Override
    public void run() {

        for (int i = 0; i < 4; i++) {

            synchronized (sharedQ) {
                //waiting status - hold off until Queue is non empty
                while (sharedQ.size() >= 1) {
                    try {
                        logger.debug("Queue is full, waiting");
                        sharedQ.wait();
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                }
                logger.debug("producing : " + i);
                sharedQ.add(i);
                sharedQ.notify();
            }
        }
    }
}

public class Consumer extends Thread {
    private static final Logger logger = Logger.getLogger(Consumer.class);
    private final Queue sharedQ;

    public Consumer(Queue sharedQ) {
        super("Consumer");
        this.sharedQ = sharedQ;
    }

    @Override
    public void run() {
        while(true) {

            synchronized (sharedQ) {
                //waiting status - hold off until Queue is non empty
                while (sharedQ.size() == 0) {
                    try {
                        logger.debug("Queue is empty, waiting");
                        sharedQ.wait();
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                }
                int number = sharedQ.poll();
                logger.debug("consuming : " + number );
                sharedQ.notify();
              
                //termination condition
                if(number == 3){break; }
            }
        }
    }
}

Output:
05:41:57,244 0    [Producer] DEBUG concurrency.Producer  - producing : 0
05:41:57,260 16   [Producer] DEBUG concurrency.Producer  - Queue is full, waiting
05:41:57,260 16   [Consumer] DEBUG concurrency.Consumer  - consuming : 0
05:41:57,260 16   [Consumer] DEBUG concurrency.Consumer  - Queue is empty, waiting
05:41:57,260 16   [Producer] DEBUG concurrency.Producer  - producing : 1
05:41:57,260 16   [Producer] DEBUG concurrency.Producer  - Queue is full, waiting
05:41:57,260 16   [Consumer] DEBUG concurrency.Consumer  - consuming : 1
05:41:57,260 16   [Consumer] DEBUG concurrency.Consumer  - Queue is empty, waiting
05:41:57,260 16   [Producer] DEBUG concurrency.Producer  - producing : 2
05:41:57,260 16   [Producer] DEBUG concurrency.Producer  - Queue is full, waiting
05:41:57,260 16   [Consumer] DEBUG concurrency.Consumer  - consuming : 2
05:41:57,260 16   [Consumer] DEBUG concurrency.Consumer  - Queue is empty, waiting
05:41:57,260 16   [Producer] DEBUG concurrency.Producer  - producing : 3
05:41:57,276 32   [Consumer] DEBUG concurrency.Consumer  - consuming : 3

That's all on this elementary representative of Inter thread communication inwards Java using hold off as well as notify method. You tin meet that both Producer as well as Consumer threads are communicating amongst each other as well as sharing information using shared Queue, Producer notifies consumer when in that place is an especial laid upwards for consumption as well as Consumer thread tells Producer i time it's done amongst consuming. This is classical representative of Producer Consumer pattern pattern equally well, which inherently involves inter-thread communication as well as information sharing betwixt threads inwards Java.


Further Learning
Multithreading as well as Parallel Computing inwards Java
Java Concurrency inwards Practice - The Book
Applying Concurrency as well as Multi-threading to Common Java Patterns
Java Concurrency inwards Practice Course past times Heinz Kabutz


Belum ada Komentar untuk "Inter Thread Communication Inwards Coffee Using Await Notify Example"

Posting Komentar

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel