Learn java thread communication with me 1

1. Introduction

This post would demo how to do the basic thread communication, e.g. the producer and consumer mode.

Normally, we would have a producer thread to produce something, and another consumer thread to consume the products.

1. Environments

  • Java 1.8

2.1 Basic wait-notify threads code template

To implement the basic producer and consumer threads, you can use the wait-notify mode, the code template is as follows:

//Thread producer
synchronized(Object){ //try to get the lock
    System.out.println("produce a product");
    condition=true;//change the condition
    Object.notify(); //notify the waiters of the lock
}

//Thread consumer
synchronized(Object){ //try to get the same lock
    while(condition==false){ //wait for the producer 
        Object.wait(); // release the lock and wait to be notified
    }
    System.out.println("consume the product ok");
}

2.2 Basic producer/consumer thread example

public class ThreadComm1 {
    private static boolean producedOk = false; //line 1
    private static Object lock = new Object(); //line 2

    public static void main(String[] args) throws InterruptedException {
        Consumer consumer = new Consumer();
        Producer producer = new Producer();
        consumer.start();
        producer.start();

        consumer.join(); //line 3
        producer.join(); //line 4
    }

    static class Producer extends Thread {
        Random random = new Random();
        public void run() {
            synchronized (lock) {
                System.out.println("producing...");
                try {
                    Thread.sleep(random.nextInt(1000));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("produced ok");
                producedOk = true;
                lock.notify();
            }
        }
    }

    static class Consumer extends Thread {
        public void run() {
            synchronized(lock) {
                while(!producedOk) {
                    try {
                        System.out.println("consumer waiting ...");
                        lock.wait();
                        System.out.println("consumer notifed,awaken.");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("consumed");
            }
        }
    }
}

The explanation:

  • line 1: this is the condition variable to be shared by both consumer and producer threads
  • line 2: the lock object to be used for synchronization of the threads
  • line 3 and line 4: After call producer and consumer threads, we call the join from main thread, this would let the main thread to wait for the threads to complete before main exit

Run the code, we get the result:

consumer waiting ...
producing...
produced ok
consumer notifed,awaken.
consumed

2.3 The other notifications about wait/notify

  • wait() 、nofify() 、nofityAll(): you must accquire the lock to call these methods
  • After call object.wait(), the object’s lock would be released, the current thread is moved to the WAITING queue.
  • After call object.notify(), the current thread would be moved to the synchronized queue,and status changed to BLOCKED.
  • After call notify(), you should release the lock, otherwise ,the WAITING thread would still wait.

3. summary

I would write more examples about inter-threads communication.

In this post we demoed how to iterate a Map by using various methods.You can find the whole code examples on github project, the class source code is located at this

You can find detail documents about the java stream here: