From b67396d3505c38d1f1f108f80a1075daf68c6e6a Mon Sep 17 00:00:00 2001 From: Matti Date: Thu, 30 May 2024 19:38:33 +0200 Subject: [PATCH] Add 4 1 --- src/part4/aufg1/Demo.java | 12 +++++++++++ src/part4/aufg1/ThreadedCounter.java | 30 ++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 src/part4/aufg1/Demo.java create mode 100644 src/part4/aufg1/ThreadedCounter.java diff --git a/src/part4/aufg1/Demo.java b/src/part4/aufg1/Demo.java new file mode 100644 index 0000000..13e37d4 --- /dev/null +++ b/src/part4/aufg1/Demo.java @@ -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(); + + } +} diff --git a/src/part4/aufg1/ThreadedCounter.java b/src/part4/aufg1/ThreadedCounter.java new file mode 100644 index 0000000..1b772ab --- /dev/null +++ b/src/part4/aufg1/ThreadedCounter.java @@ -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"); + } +} \ No newline at end of file