diff --git a/_programs_java/java_concurrency/multithreading/code19_CLASSIC_PROBLEMS_producer_consumer_problem.java b/_programs_java/java_concurrency/multithreading/code19_CLASSIC_PROBLEMS_producer_consumer_problem.java index e8020e5e..7959d02d 100644 --- a/_programs_java/java_concurrency/multithreading/code19_CLASSIC_PROBLEMS_producer_consumer_problem.java +++ b/_programs_java/java_concurrency/multithreading/code19_CLASSIC_PROBLEMS_producer_consumer_problem.java @@ -1,5 +1,6 @@ // Java program to implement solution of producer // consumer problem. +import java.util.Scanner; import java.util.LinkedList; public class Threadexample @@ -7,6 +8,14 @@ public class Threadexample public static void main(String[] args) throws InterruptedException { + + Scanner sc = new Scanner(System.in); + //user input for number of products to be praduced + System.out.println("Enter number of product you want to produce: "); + int products = sc.nextInt(); + + final PC pc = new PC(products); + // Object of a class that has both produce() // and consume() methods final PC pc = new PC(); @@ -60,9 +69,15 @@ public static class PC { // Create a list shared by producer and consumer // Size of list is 2. + // Number of products to be produced by producer LinkedList list = new LinkedList<>(); int capacity = 2; + int productCount; + // Constructer initialising values + public PC(int productCount) { + this.productCount = productCount; + } // Function called by producer thread public void produce() throws InterruptedException { @@ -71,17 +86,25 @@ public void produce() throws InterruptedException { synchronized (this) { + // producer thread terminating condition + if(productCount == 0){ + System.out.println("All products are accounted for...."); + return; + } + // producer thread waits while list // is full while (list.size()==capacity) wait(); - System.out.println("Producer produced-" - + value); + System.out.println("Producer produced-"+ value); // to insert the jobs in the list list.add(value++); + // to decrement the product count + productCount--; + // notifies the consumer thread that // now it can start consuming notify(); @@ -108,8 +131,7 @@ public void consume() throws InterruptedException //to retrive the ifrst job in the list int val = list.removeFirst(); - System.out.println("Consumer consumed-" - + val); + System.out.println("Consumer consumed-"+ val); // Wake up producer thread notify(); @@ -120,4 +142,4 @@ public void consume() throws InterruptedException } } } -} \ No newline at end of file +}