Skip to content

Terminating condition for code #10

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,12 +1,21 @@
// Java program to implement solution of producer
// consumer problem.
import java.util.Scanner;
import java.util.LinkedList;

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();
Expand Down Expand Up @@ -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<Integer> 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
{
Expand All @@ -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();
Expand All @@ -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();
Expand All @@ -120,4 +142,4 @@ public void consume() throws InterruptedException
}
}
}
}
}