0% found this document useful (0 votes)
7 views2 pages

EXERCISE-11 (A) : 11 (A) .Aim:-Write A JAVA Program Producer Consumer Problem Program

Uploaded by

manvithsai1001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views2 pages

EXERCISE-11 (A) : 11 (A) .Aim:-Write A JAVA Program Producer Consumer Problem Program

Uploaded by

manvithsai1001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Exercise:

Date: RollNo:

EXERCISE-11(a)

11(a).Aim:- Write a JAVA program Producer Consumer Problem

Program:
class Q {
int n;
boolean valueSet = false;

synchronized int get() {


while (!valueSet) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // Restore interrupted status
}
}
System.out.println("Got: " + n);
valueSet = false;
notify();
return n;
}

synchronized void put(int n) {


while (valueSet) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // Restore interrupted status
}
}
this.n = n;
valueSet = true;
System.out.println("Put: " + n);
notify();
}
}

class Producer implements Runnable {


Q q;

Producer(Q q) {
this.q = q;
new Thread(this, "Producer").start();
}

public void run() {


int i = 0;

KALLAMHARANADHAREDDYINSTITUTEOFTECHNOLOGY,CHOWDAVARAM
GUNTUR
Exercise:
Date: RollNo:
try {
while (true) {
q.put(i++);
Thread.sleep(1000); // Introducing delay to observe output easily
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // Restore interrupted status
}
}
}

class Consumer implements Runnable {


Q q;

Consumer(Q q) {
this.q = q;
new Thread(this, "Consumer").start();
}

public void run() {


try {
while (true) {
q.get();
Thread.sleep(1000); // Introducing delay to observe output easily
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // Restore interrupted status
}
}
}

public class Th9 {


public static void main(String args[]) {
Q q = new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to stop.");
}
}

KALLAMHARANADHAREDDYINSTITUTEOFTECHNOLOGY,CHOWDAVARAM
GUNTUR

You might also like