This website is for reference purposes only. Users are responsible for any misuse. The owner is not liable for any consequences.
Back to Java Programming (Laboratory)
1.6.1HardCODE

Program for producer and consumer problem using Threads

Question

Solution

JAVA

package q63229;
import java.util.Scanner;
class ProdCons {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.print("number of items to be produced and consumed: ");
        int numItems = sc.nextInt();
        Product p = new Product(numItems);
        Thread producerThread = new Thread(new Producer(p));
        Thread consumerThread = new Thread(new Consumer(p));
        producerThread.start();
        consumerThread.start();
        sc.close();
    }
}

class Product {
    private int value;
    private boolean available = false;
	int n;
    Product(int n) {
		this.n = n;
	}

	public synchronized void put (int val) {
		while (available) {
			try {
				wait();
			} catch (InterruptedException e) { }
		}
		value = val;
		System.out.println("PUT: " + value);
		available = true;
		notify();
	}

	public synchronized int get() {
		while (!available) {
			try {
				wait();
			} catch (InterruptedException e) { }
		}
		System.out.println("GET: " + value);
		available = false;
		notify();
		return value;
	}
    

    
            
}

class Producer implements Runnable {
    Product p;
	Producer (Product p) {
		this.p = p;
	}
    public void run() {
		for (int i=0; i< p.n; i++) {
			p.put(i);
		}
	}
    
    
}

class Consumer implements Runnable {
    Product p;

	Consumer(Product p) {
		this.p = p;
	}

	public void run() {
		for (int i=0; i<p.n; i++) {
			p.get();
		}
	}

2/2 test cases passed

3/3 hidden test cases passed