Aug 29, 2024

Producer-Consumer Problem

Turns out it's not the same program as the OOP Lab.

Source Code

import java.util.Scanner;

public class ProducerConsumer {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);

		System.out.print("Enter buffer size: ");
		int size = scanner.nextInt();
		int buffer = 0;

		while (true) {
			System.out.println();
			System.out.println("--- MENU ---");
			System.out.println("1. Produce");
			System.out.println("2. Consume");
			System.out.println("3. Exit");

			System.out.println();
			System.out.print("Enter your choice: ");
			int choice = scanner.nextInt();

			switch (choice) {
				case 1:
					if (buffer < size) {
						buffer++;
						System.out.println("INFO | Item produced. Buffer: " + buffer);
					} else {
						System.out.println("INFO | Buffer full!");
					}
					break;
				case 2:
					if (buffer > 0) {
						buffer--;
						System.out.println("INFO | Item consumed. Buffer: " + buffer);
					} else {
						System.out.println("INFO | Buffer empty!");
					}
					break;
				case 3:
					System.exit(0);
				default:
					System.out.println("ERROR | Invalid choice!");
			}
		}
	}
}

Output

Enter buffer size: 2

--- MENU ---
1. Produce
2. Consume
3. Exit

Enter your choice: 1
INFO | Item produced. Buffer: 1

--- MENU ---
1. Produce
2. Consume
3. Exit

Enter your choice: 1
INFO | Item produced. Buffer: 2

--- MENU ---
1. Produce
2. Consume
3. Exit

Enter your choice: 1
INFO | Buffer full!

--- MENU ---
1. Produce
2. Consume
3. Exit

Enter your choice: 2
INFO | Item consumed. Buffer: 1

--- MENU ---
1. Produce
2. Consume
3. Exit

Enter your choice: 3