Add 4 1
This commit is contained in:
parent
b3bc487347
commit
b67396d350
12
src/part4/aufg1/Demo.java
Normal file
12
src/part4/aufg1/Demo.java
Normal 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();
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
30
src/part4/aufg1/ThreadedCounter.java
Normal file
30
src/part4/aufg1/ThreadedCounter.java
Normal 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");
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user