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;
public Semaphore(int n) {
count = n;
}
public synchronized void down() {
while (count == 0) {
try {
wait();
} 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.