0% found this document useful (0 votes)
9 views3 pages

Assignment 14

Uploaded by

bikkibiswas143
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)
9 views3 pages

Assignment 14

Uploaded by

bikkibiswas143
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/ 3

1.

Write a java program to illustrate inter thread communication using Producer


Consumer Problem.
Code :
import java.util.LinkedList;

class SharedBuffer {
private LinkedList<Integer> buffer = new LinkedList<>();
private int capacity;

public SharedBuffer(int capacity) {


this.capacity = capacity;
}

public void produce(int item) throws InterruptedException {


synchronized (this) {
while (buffer.size() == capacity) {
wait();
}
buffer.add(item);
System.out.println("Produced: " + item);
notify();
}
}

public int consume() throws InterruptedException {


synchronized (this) {
while (buffer.isEmpty()) {
wait();
}
int item = buffer.removeFirst();
System.out.println("Consumed: " + item);
notify();
return item;
}
}
}

class Producer extends Thread {


private SharedBuffer buffer;

public Producer(SharedBuffer buffer) {


this.buffer = buffer;
}
@Override
public void run() {
try {
for (int i = 1; i <= 5; i++) {
buffer.produce(i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

class Consumer extends Thread {


private SharedBuffer buffer;

public Consumer(SharedBuffer buffer) {


this.buffer = buffer;
}

@Override
public void run() {
try {
for (int i = 1; i <= 5; i++) {
int item = buffer.consume();
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public class procom {


public static void main(String[] args) {
SharedBuffer buffer = new SharedBuffer(3);
Producer producer = new Producer(buffer);
Consumer consumer = new Consumer(buffer);

producer.start();
consumer.start();
}
}

Output -

You might also like