×

Producer Consumer Problem in Java Using Synchronized Block

The producer-consumer dilemma is a well-known instance of a multi-process synchronization issue in computing. Two processes—the producer and the consumer—are described in the issue, and they share a single, fixed-size buffer that serves as a queue.

  • The producer's responsibility is to produce data, store it in the buffer, and start over.
  • The customer is simultaneously absorbing the info one piece at a time.

Problem Statement

To ensure that neither the producer nor the consumer would attempt to remove data from an empty buffer or add data to one already full.

Approach

If the buffer is full, the producer must either sleep or discard data. The producer restarts filling the buffer after receiving a notification from the consumer the next time an item is removed from the buffer. The consumer has the same option to sleep if it discovers that the buffer is empty. The consumer is awakened each time the producer inserts data into the buffer.

An insufficient response could lead to a standstill when both processes are awaiting activation.

Using the Producer-Consumer Class

  • A LinkedList list is used to maintain a list of queued jobs.
  • A variable capacity is used to determine whether or not the list is full.
  • a technique to regulate the addition of items to and removal of items from this list so that neither is done when the list is full or empty.

Producer Consumer Problem Java Program

ProducerConsumerProblem.java

// importing the util package to use linked list
import java.util.LinkedList;
// Public class declaration
public class ProducerConsumerProblem{
// Main section of the program from where execution begins
public static void main(String[] args) throws InterruptedException
{
// A class object with the produce() and consume() functions.
final PC p = new PC();
// producer thread creation
// creation of the thread using thread class
Thread thread1 = new Thread(new Runnable() {
@Override
// rum method which is used to run the thread
public void run()
{
// try block is used to overcome the errors
try {
// calling the produce method
p.produce();
}
catch (InterruptedException ex) {
ex.printStackTrace();
}
}
});
// consumer thread creation
Thread thread2 = new Thread(new Runnable() {
@Override
public void run()
{
try {
p.consume();
}
catch (InterruptedException ex) {
ex.printStackTrace();
}
}
});
// starting both threads which are created
thread1.start();
thread2.start();
// 
thread1.join();
thread2.join();
}
public static class PC {
// Create a list shared by producer and consumer
LinkedList<Integer> lt = new LinkedList<>();
int capacity = 2;
public void produce() throws InterruptedException
{
int v = 0;
while (true) {
synchronized (this)
{
// producer thread waits while buffer list is full
while (lt.size() == capacity)
wait();
System.out.println("Producer produced-" + v);
// Inserting the jobs into the buffer list
lt.add(v++);
// notifying the consumer thread to start consuming
notify();
// sleep method is used to stop the execution for certain amount of time
Thread.sleep(1000);
}
}
}


public void consume() throws InterruptedException
{
while (true) {
synchronized (this)
{
// consumer  waits while buffer  list is empty
while (lt.size() == 0)
    wait();
int v = lt.removeFirst();
System.out.println("Consumer consumed-"+ v);
// Intimate the Producer thread
notify();
// consumner thread is forced to sleep until the producer thread produces 
Thread.sleep(1000);
}
}
}
}
}

Output

Producer produced-0
Producer produced-1
Consumer consumed-0
Consumer consumed-1
Producer produced-2
Producer produced-3
Consumer consumed-2
Consumer consumed-3
Producer produced-4
Producer produced-5
Consumer consumed-4
Consumer consumed-5
Producer produced-6
Producer produced-7
Consumer consumed-6
Consumer consumed-7

Explanation

  • A linked list of tasks and a list's capacity are added to the PC class (A class will both produce and consume methods) to ensure that the producer won't produce if the list is full.
  • The initialization of the value in the Producer class is 0.
  • In order to add values to the list, we also have an endless outer loop. We have a synchronized block inside of this loop that only allows a producer or consumer thread to execute at once.
  • Before adding the jobs to the list, there is an inner loop that determines whether the job list is full. If it is, the producer thread relinquishes the intrinsic lock on the PC and enters the waiting state.
  • If the list is empty, the control moves to the loop below, and a value is added to the list. We once more use an infinite loop in the Consumer class to pull a value from the list.
  • We also have an inner loop within that determines whether the list is empty.
    1. If it is empty, we force the consumer thread to release the lock on the computer and transfer control to the producer thread so it can create more tasks.
    2. If the list has any items and is not empty, we repeat the loop and remove a piece of the list.
  • We utilize the notify method at the conclusion of every statement in both approaches.
  • If the list is empty, the control moves to the loop below, and a value is added to the list.
  • We once more use an infinite loop in the Consumer class to pull a value from the list.
  • We also have an inner loop within that determines whether the list is empty.
    1. If it is empty, we force the consumer thread to release the lock on the computer and transfer control to the producer thread so it can create more tasks.
    2. If the list has any items and is not empty, we repeat the loop and remove a piece of the list.
    3. We utilize the  notify at the conclusion of every statement in both approaches.

Related Topics

Java String isEmpty() method

Java String isEmpty() method checks whether current String is empty or not. Syntax: public boolean isEmpty() Returns It returns true, if length of String is 0 otherwise false. Java String isEmpty() method example 1    ...

1 minute read.

Java Thread Creation

Java provides the two ways to create a Thread: Implementing the Runnable interface.Extending the Thread class. Implementing Runnable interface The easiest way of creating a thread is to make a class that implements...

5 minutes read.

Java Integer highestOneBit()

The highestOneBit() method of Java Integer class returns an int value with at most a single one-bit, in the position of the highest-order one-bit in the specified int value.  Syntax public static...

1 minute read.

Callable Statement in Java

The Callable statement in Java is used to call the functions and Stored procedures. Example: If we want to know about the age of a person based on their date of birth,...

3 minutes read.

Get yesterdays date by no of days in Java

In this tutorial, we are going to learn how to get yesterday’s date by the no of days in Java. Using the Calendar class, one can get the current date....

1 minute read.

Java String subSequence() method

This method returns a new character sequence i.e. subsequence of current sequence Syntax: public CharSequence subSequence(int beginIndex, int endIndex) Parameter: beginIndex ? begin index, inclusive. endIndex ? end index, exclusive. Return: specified subsequnce Throws: It throws IndexOutOfBoundsException...

1 minute read.

Model Class in Java

In this section, we will be acknowledged about the model class in Java, its purpose and its uses. Also, we will learn how is this created and leveraged in java. Model...

4 minutes read.

Read the XLSX file in Java

Excel files contain cells; reading an excel file in Java differs from reading a word file. JDK doesn't have a direct API that can read or write Word or Excel...

3 minutes read.

Java Characters

Normally, when we work with characters, we use primitive data types char. When we have to work with the objects of char, we use Character class. Character class has many important...

2 minutes read.

Jagged Array in Java

Prerequisite We must first understand what Arrays are and Multi-dimensional Arrays are before we can learn about Jagged arrays. Java Arrays: A collection of data types that are similar is called an...

5 minutes read.

Java delete directory

The File classes in Java may symbolize a directory or a file on the system. Inside the java.io package, the Files class is accessible. The File class has several helpful...

2 minutes read.

Java Boolean toString() Method

The toString() method of Java Boolean class returns a String corresponding to this Boolean object. It returns a string value “true”, if the defined object is true else it returns...

2 minutes read.

Method and Block Synchronization in Java

The Synchronization is performed in multi-threading concept. The multi-threading is a concept of parallel running of a program for the execution. In the multi-threading concept, the threads are run by...

3 minutes read.

Decagonal Numbers in Java

This section explains what is a decagonal number and how to write Java programmes that compute decagonal numbers. Both academics and Java programmer interviews regularly question about the Decagonal number...

3 minutes read.

Java Swings

Swing is a Java Foundation Class library and an extension to the Abstract Window Toolkit (AWT) (JFC).As compared to AWT, Swing has significantly better functionality, new components, increased component features,...

9 minutes read.

Java inheritance with Example

Java inheritance Java inheritance is a mechanism in which a child object acquires all the properties and behaviors of a parent object. It helps in reusing the code and establishes...

7 minutes read.

Java Numbers

We use primitive data types like byte, int, long, double, etc to work with the numbers, When we need objects, we use wrapper class like Integer, Double, Long, Byte, etc....

2 minutes read.

Java Float Keyword

Float: In general, there are two categories of data types: primitive data types and non-primitive data types. So, float is the data type which is a primitive data type. Declarating the variables and...

3 minutes read.

Abstract Class Program in Java

Abstract Class Program in Java Abstraction is a technique by which a developer hides the implementation details from the user and shows only the functionality.It is not only confined to the...

6 minutes read.

Vector in Java

Java Vector Class The Vector class is a legacy class that implements a growable array of objects. The components that it contains can be accessed using an integer index. The size of...

26 minutes read.