Exercise 1
Implementierung der Threads
public class ConcurrentThreadsSimpleProblem {
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) {
ConcurrentThreadsSimpleProblem.value++;
}
end = System.currentTimeMillis();
} catch (Exception e) {
System.out.println("Exception: " + e);
}
System.out.println("ID: " + id + ", Runtime [ms]: " + (end - start));
}
}
Build & Run
javac ConcurrentThreadsSimpleProblem.java
java ConcurrentThreadsSimpleProblem
ID: 1, Runtime [ms]: 13
ID: 0, Runtime [ms]: 20
final value = 1881252
java ConcurrentThreadsSimpleProblem
ID: 0, Runtime [ms]: 14
ID: 1, Runtime [ms]: 19
final value = 1853855
java ConcurrentThreadsSimpleProblem
ID: 1, Runtime [ms]: 10
ID: 0, Runtime [ms]: 10
final value = 1028029