This commit is contained in:
Matti 2024-05-30 19:38:33 +02:00
parent b3bc487347
commit b67396d350
2 changed files with 42 additions and 0 deletions

12
src/part4/aufg1/Demo.java Normal file
View File

@ -0,0 +1,12 @@
package part4.aufg1;
public class Demo {
public static void main(String[] args) {
ThreadedCounter tc = new ThreadedCounter(-1,1);
ThreadedCounter tC = new ThreadedCounter(4,2);
tc.start();
tC.start();
}
}

View File

@ -0,0 +1,30 @@
package part4.aufg1;
public class ThreadedCounter extends Thread {
private final int threadNumber;
private final int increment;
static int sharedInt = 0;
static int iterations = 0;
public ThreadedCounter(int increment, int threadNumber) {
this.increment = increment;
this.threadNumber = threadNumber;
}
public void run() {
while (sharedInt < 1000){
synchronized (getClass()) {
iterations++;
sharedInt += increment;
System.out.println("Thread " + threadNumber + " made the shared Int: " + sharedInt);
try {
sleep(10);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
System.out.println("it took " + iterations + " iterations");
}
}