Exercise 2
Sicherung der Critical Section durch eine Semaphore
import java.util.concurrent.Semaphore;
public class ConcurrentThreadsSemaphore {
public static Semaphore semaphore = new Semaphore(1);
public static int value;
public static final int ITERATIONS = 1000000;
public static void main(String[] args) throws InterruptedException {
Thread t1 = new IncrementProblemThread(0, ITERATIONS);
Thread t2 = new IncrementProblemThread(1, ITERATIONS);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("final value = " + value);
}
}
class IncrementProblemThread extends Thread {
int id;
private int iterations;
private long start;
private long end;
public IncrementProblemThread(int id, int iterations) {
this.id = id;
this.iterations = iterations;
}
public void run() {
try {
start = System.currentTimeMillis();
for (int i = 0 ; i < iterations ; ++i) {
ConcurrentThreadsSemaphore.semaphore.acquire();
ConcurrentThreadsSemaphore.value++;
ConcurrentThreadsSemaphore.semaphore.release();
}
end = System.currentTimeMillis();
} catch (Exception e) {
System.out.println("Exception: " + e);
}
System.out.println("ID: " + id + ", Runtime [ms]: " + (end - start));
}
}Build & Run
javac ConcurrentThreadsSemaphore.javajava ConcurrentThreadsSemaphore
ID: 1, Runtime [ms]: 137
ID: 0, Runtime [ms]: 133
final value = 2000000java ConcurrentThreadsSemaphore
ID: 0, Runtime [ms]: 120
ID: 1, Runtime [ms]: 108
final value = 2000000java ConcurrentThreadsSemaphore
ID: 0, Runtime [ms]: 128
ID: 1, Runtime [ms]: 128
final value = 2000000