Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
1.5 kB
0
Indexable
Never
import java.util.concurrent.Semaphore;

class SharedResource {
    private int data = 0;

    public void increment() {
        data++;
    }

    public void decrement() {
        data--;
    }

    public int getData() {
        return data;
    }
}

class WorkerThread extends Thread {
    private Semaphore semaphore;
    private SharedResource sharedResource;

    public WorkerThread(Semaphore semaphore, SharedResource sharedResource) {
        this.semaphore = semaphore;
        this.sharedResource = sharedResource;
    }

    @Override
    public void run() {
        try {
            semaphore.acquire();
            sharedResource.increment();
            System.out.println("Data after increment: " + sharedResource.getData());
            sharedResource.decrement();
            System.out.println("Data after decrement: " + sharedResource.getData());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            semaphore.release();
        }
    }
}

public class BinarySemaphores {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(1); // Binary semaphore
        SharedResource sharedResource = new SharedResource();

        WorkerThread worker1 = new WorkerThread(semaphore, sharedResource);
        WorkerThread worker2 = new WorkerThread(semaphore, sharedResource);
        WorkerThread worker3 = new WorkerThread(semaphore, sharedResource);

        worker1.start();
        worker2.start();
        worker3.start();
    }
}
Leave a Comment