In the following example two threads share int counter.
The increment_thread thread increases counter by one .
The decrement_thread thread decreases counter by one .
I use semaphore to control access to counter instead of making the two methods synchronized.
Is this the proper way of using semaphore?
When should we use synchronized methods and when a semaphore?(we don't want more than one thread to access counter at the same time).
If both are proper , which is preferable?
import java.util.concurrent.Semaphore;
public class SemaphoreMultithreadingExample {
static int counter = 0;
static Semaphore semaphore = new Semaphore(1);
public static void incrementCounter(){
try {
semaphore.acquire();
counter++;
semaphore.release();
} catch (InterruptedException ex) {
}
}
public static void decrementCounter(){
try {
semaphore.acquire();
counter--;
semaphore.release();
} catch (InterruptedException ex) {
}
}
public static void main(String[] args) throws InterruptedException {
Thread increment_thread = new Thread() {
@Override
public void run() {
for (int i = 0; i < 5000; i++) {
incrementCounter();
}
}
};
Thread decrement_thread = new Thread() {
@Override
public void run() {
for (int i = 0; i < 5000; i++) {
decrementCounter();
}
}
};
increment_thread.start();
decrement_thread.start();
increment_thread.join();
decrement_thread.join();
System.out.println("Counter : " + counter);
System.out.println("If the result is 0 then it works ");
}
}