Java multithreaded producer and consumer model, communication between threads

Posted by cyberdesi on Thu, 30 Jan 2020 16:37:41 +0100

Producer and consumer patterns in java multithreading:
First, there is a blocking queue. The producer puts the production in the queue, and the consumer takes it from the queue. Blocking occurs when the number of things in the queue reaches its capacity.

import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;

public class UseBlockingQueue {
    private static BlockingQueue<String> queue = new ArrayBlockingQueue<>(1);//1 is the capacity of the queue. If it exceeds the capacity, it will block.
            // new PriorityBlockingQueue<>();
            // new LinkedBlockingQueue<>();
            // new ArrayBlockingQueue<>(10);

    private static class Producer extends Thread {
        @Override
        public void run() {
            Random random = new Random(20191116);
            while (true) {
                try {
                    int message = random.nextInt(100);
                    queue.put(String.valueOf(message));//Put messages on the queue
                    System.out.println("Put in message: " + message);
                    Thread.sleep(random.nextInt(3) * 100);//sleep
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static class Customer extends Thread {
        @Override
        public void run() {
            Random random = new Random(20191116);
            while (true) {
                try {
                    String message = queue.take();//Take messages from the queue
                    System.out.println("Receive message: " + message);
                    Thread.sleep(random.nextInt(3) * 100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        Thread producer = new Producer();
        Thread customer = new Customer();
        producer.start();
        customer.start();
    }
}

synchronized keyword modification: lock the object to ensure thread safety. If the CPU has any scheduling, the thread will not be unsafe.

public class MyQueue2 {
    private int[] array = new int[2];
    private volatile int size;
    private int front;
    private int rear;

    private Object full = new Object();
    private Object empty = new Object();

    public void put(int message) throws InterruptedException {
        while (size == array.length) {
            synchronized (full) {
                full.wait();
            }
        }

        synchronized (this) {
            array[rear] = message;
            rear = (rear + 1) % array.length;
            size++;
        }

        synchronized (empty) {
            empty.notify();
        }
    }

    public synchronized int take() throws InterruptedException {
        while (size == 0) {
            synchronized (empty) {
                empty.wait();
            }
        }

        int message;
        synchronized (this) {
            message = array[front];
            front = (front + 1) % array.length;
            size--;
        }

        synchronized (full) {
            full.notify();
        }

        return message;
    }
}

Communication between threads
public class ThreadDemo {
public static void main(String[] args){
class Person{
public String name;
private String gender;
public void set(String name,String gender){
this.name =name;
this.gender =gender;
}
public void get(){
System.out.println(this.name+"...."+this.gender);
}
}//The Person class has two properties and two methods
final Person p =new Person();//new a Person class object p
new Thread(new Runnable() {/ / anonymous thread
public void run() {/ / override the run method
int x=0;
while(true){
if(x==0){
p.set("Zhang San", "male");
}else{
p.set("lili", "nv");
}
x=(x+1)%2;
}
}
}).start();
new Thread(new Runnable(){
public void run(){
while(true){
p.get();
}
}
}). start(); / / start an anonymous thread
}
}

Topics: Java