4) Write a Java program that implements bounded buffer problem (consider a circular queue
and single producer and consumer threads).
import java.util.Scanner;
class Qb {
int n;
int a[] = new int[5];
boolean valueSet = false;
private Scanner s;
int front = -1;
int rear = -1;
int result;
synchronized int get() {
while (!valueSet)
try {
wait();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println();
for (int i = 0; i <= 4; i++) {
result = deleteQ();
System.out.println("Consumed#" + (i + 1) + ": " + result);
valueSet = false;
}
notify();
return n;
}
synchronized void put(int n) {
while (valueSet)
try {
wait();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
for (int i = 0; i <= 4; i++) {
this.n = n;
valueSet = true;
System.out.println("enter the value u want to push in ");
s = new Scanner(System.in);
result = s.nextInt();
System.out.println("Producer#" + (i + 1) + ": " + result);
insertQ(result);
}
notify();
}
void insertQ(int m) {
if ((front == 0 && rear == 4) || (front == rear + 1)) {
System.out.println("Production Queue is Full");
} else if (rear == -1) {
rear++;
front++;
a[rear] = m;
} else {
rear++;
a[rear] = m;
}
}
int deleteQ() {
int m;
if (front == -1 && rear == -1) {
System.out.println("NO More Produced Queue is empty");
return -1;
} else if (front == rear) {
if (front == 0) {
rear = -1;
front = -1;
System.out.println("NO More Produced Queue is empty");
return -1;
}
m = front;
rear = -1;
front = -1;
return a[m];
} else if (front == 5) {
front = 0;
return a[front];
} else {
m = a[front];
++front;
return m;
}
}
}
class Producers implements Runnable {
Qb q;
Producers(Qb q) {
this.q = q;
new Thread(this, "Producer").start();
}
public void run() {
int i = 0;
while (i == 0) {
q.put(i);
}
}
}
class Consumers implements Runnable {
Qb q;
Consumers(Qb q) {
this.q = q;
new Thread(this, "Consumer").start();
}
public void run() {
int i = 0;
while (i == 0) {
q.get();
}
}
}
class BoundBuffer {
public static void main(String args[]) {
Qb q = new Qb();
new Producers(q);
new Consumers(q);
System.out.println("Press Control-C to stop.");
}
}
OUTPUT-:
enter the value u want to push inPress Control-C to stop.
1
Producer#1: 1
enter the value u want to push in
3
Producer#2: 3
enter the value u want to push in
4
Producer#3: 4
enter the value u want to push in
6
Producer#4: 6
enter the value u want to push in
7
Producer#5: 7
Consumed#1: 1
Consumed#2: 3
Consumed#3: 4
Consumed#4: 6
Consumed#5: 7
0 comments:
Post a Comment