Inter Thread Communication Inward Coffee Using Facial Expression Notify Example

Advertisement

Masukkan script iklan 970x90px

Inter Thread Communication Inward Coffee Using Facial Expression Notify Example

Minggu, 19 April 2020

Wait together with notify methods inwards Java are used for inter-thread communication i.e. if ane thread wants to say something to roughly other thread, it uses notify() and notifyAll() method of java.lang.Object. Classical illustration of hold back together with notify method is Producer Consumer blueprint pattern, where One thread hit together with seat something on shared bucket, together with and then say other thread that at that spot is an special for your involvement inwards shared object, consumer thread than option than special together with do his job, without wait() together with notify(), consumer thread needs to last busy checking, fifty-fifty if at that spot is no alter inwards dry ground of shared object.

This brings an interesting indicate on using hold back together with notify mechanism, a telephone telephone to notify() happens, when thread changed dry ground of shared object i.e. inwards this illustration producer alter bucket from empty to non empty, together with consumer alter dry ground from non-empty to empty.

Also wait together with notify method must last called from synchronized context, wondering why, read this link for roughly reasons which makes sense. Another of import affair to snuff it along inwards hear spell calling them is, using loop to cheque weather condition instead of if block.

This is actually tricky for beginners, which oftentimes don't empathize divergence together with wonders why hold back together with notify acquire called cast loops. Joshua Bloch has a rattling informative special on his majority Effective Java, I strongly advise reading that.

In short, a waiting thread may woke up, without whatever alter 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 simulated alert together with endeavor to acquire something from queue without farther checking whether queue is empty or non than unexpected lawsuit is possible.

Here is touchstone idiom for calling wait, notify together with notifyAll methods inwards Java :




How to telephone telephone hold back method inwards Java :

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

together with hither is consummate illustration of calling hold back together with notify method inwards Java using ii threads, producer together with consumer

 Wait together with notify methods inwards Java are used for inter Inter Thread Communication inwards Java using Wait Notify Example


Java Inter Thread Communication Example - Wait together with Notify

 Wait together with 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 let on into shared queue together with Consumer thread consumes numbers from shared bucket. Condition is that ane time an special is produced, consumer thread has to last notified together with similarly subsequently consumption producer thread needs to last notified. This inter thread communication is achieved using hold back together with notify method. Remember wait together with notify method is defined inwards object class, together with 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 back 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 back until Queue is non empty
                while (sharedQ.size() == 0) {
                    try {
                        logger.debug("Queue is empty, waiting");
                        sharedQ.wait();
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                }
                int let on = sharedQ.poll();
                logger.debug("consuming : " + let on );
                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 uncomplicated illustration of Inter thread communication inwards Java using hold back together with notify method. You tin hand the sack run into that both Producer together with Consumer threads are communicating alongside each other together with sharing information using shared Queue, Producer notifies consumer when at that spot is an special cook for consumption together with Consumer thread tells Producer ane time it's done alongside consuming. This is classical illustration of Producer Consumer blueprint pattern every bit well, which inherently involves inter-thread communication together with information sharing betwixt threads inwards Java.


Further Learning
Multithreading together with Parallel Computing inwards Java
Java Concurrency inwards Practice - The Book
Applying Concurrency together with Multi-threading to Common Java Patterns
Java Concurrency inwards Practice Course yesteryear Heinz Kabutz