Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
2.1 kB
0
Indexable
Never
class SharedResource {
    private int data;
    private boolean dataAvailable = false;

    public synchronized void produce(int item) throws InterruptedException {
        while (dataAvailable) {
            wait();
        }

        data = item;
        dataAvailable = true;
        System.out.println("Produced: " + item);
        notify();
    }

    public synchronized int consume() throws InterruptedException {
        while (!dataAvailable) {
            wait();
        }

        int item = data;
        dataAvailable = false;
        System.out.println("Consumed: " + item);
        notify();
        return item;
    }
}

class Producer implements Runnable {
    private SharedResource resource;

    public Producer(SharedResource resource) {
        this.resource = resource;
    }

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

class Consumer implements Runnable {
    private SharedResource resource;

    public Consumer(SharedResource resource) {
        this.resource = resource;
    }

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

public class Main {
    public static void main(String[] args) {
        SharedResource resource = new SharedResource();

        Thread producerThread1 = new Thread(new Producer(resource));
        Thread producerThread2 = new Thread(new Producer(resource));
        Thread consumerThread1 = new Thread(new Consumer(resource));
        Thread consumerThread2 = new Thread(new Consumer(resource));

        producerThread1.start();
        producerThread2.start();
        consumerThread1.start();
        consumerThread2.start();
    }
}