Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.LinkedList;
- import java.util.Queue;
- public class ProCons {
- Queue<Integer> queue = new LinkedList<Integer>();
- int max_capacity = 5;
- public void produce(int i) throws InterruptedException {
- while (true) {
- synchronized (this) {
- if (queue.size() == max_capacity) {
- wait();
- }
- System.out.println("Produced: " + i);
- queue.add(i);
- notify();
- Thread.sleep(1000);
- }
- }
- }
- public void consume() throws InterruptedException {
- while (true) {
- synchronized (this) {
- if (queue.size() == 0) {
- wait();
- }
- int i = queue.poll();
- System.out.println("consumed: " + i);
- notify();
- Thread.sleep(1000);
- }
- }
- }
- public static void main(String[] args) {
- ProCons pc = new ProCons();
- Thread producerThread = new Thread(new Runnable() {
- @Override
- public void run() {
- try {
- pc.produce(100);
- } catch (InterruptedException e) {
- System.out.println("Exception in producer" + e.getMessage());
- }
- }
- });
- Thread consumerThread = new Thread(new Runnable() {
- @Override
- public void run() {
- try {
- pc.consume();
- } catch (InterruptedException e) {
- System.out.println("Exception in consumer" + e.getMessage());
- }
- }
- });
- try {
- producerThread.start();
- consumerThread.start();
- producerThread.join();
- consumerThread.join();
- } catch (InterruptedException e) {
- System.out.println("Exception " + e.getMessage());
- }
- }
- }
Add Comment
Please, Sign In to add comment