Java and process schedule modeling

I really appreciate all the help provided, but now I'm struggling with the final part of the task, which is to make the increments and decrements alternate. Ive edited to include all of my main class and the increment of the class that contains the for loop, which calls Main.increment a certain number of times (there is a decrement of the class that has the same style as icpmenter so I did not include it). Could you help with how I can achieve this. If I understood correctly, I am looking for the sharedValue value to switch between 1 and 0.

public class Main extends Thread {

private static int sharedValue = 0;
private static Semaphore semaphore = new Semaphore(1);

public static void increment() {
    semaphore.down();
    sharedValue++;
    semaphore.up();
}

public static void decrement() {
    semaphore.down();
    sharedValue--;
    semaphore.up();
}

static int numberOfCycles = 20000;

public static void main(String[] args) throws InterruptedException {

    incrementer inc = new incrementer(numberOfCycles);
    inc.start();
    inc.join();

    decrementer dec = new decrementer(numberOfCycles);
    dec.start();
    dec.join();

    System.out.println(sharedValue);

}}

Semaphore class

private int count;
// Constructor
public Semaphore(int n) {
    count = n;
}

// Only the standard up and down operators are allowed.
public synchronized void down() {

    while (count == 0) {

        try {
            wait(); // Blocking call.
        } catch (InterruptedException exception) {
        }
    }
    count--;
}

public synchronized void up() {
    count++;
    notify();
  }
}

Incremental class

The priority of the public class extends Thread {

private int numberOfIncrements;

public incrementer(int numOfIncrements){
     numberOfIncrements = numOfIncrements;
} 
public void run(){
    for(int i = 0; i <= numberOfIncrements; i++){
    Main.increment();
}
}

}

Thanks again.

+4
2

, . , - :

class ProtectedCount {
    private static int sharedValue = 0;
    private static Semaphore semaphore = new Semaphore(1);
    public void increment() {
        semaphore.down(); // wait till the semaphore is available
        sharedValue++;
        semaphore.up(); // tell everyone that the semaphore is available
    }
    // same thing for decrement()
}

. . . .

+3

Semaphore , "" "n", .

// Constructor
public Semaphore(int n) {
    count = n;
}

public synchronized void up() {
    count++; //Ensure count doesn't exceed n.
    notify();
  }
0

Source: https://habr.com/ru/post/1619544/


All Articles