diff --git a/VL14/Aufgabe01/Aufgabe01.java b/VL14/Aufgabe01/Aufgabe01.java new file mode 100644 index 0000000..eff3f68 --- /dev/null +++ b/VL14/Aufgabe01/Aufgabe01.java @@ -0,0 +1,18 @@ +package VL14.Aufgabe01; + +/** + * Vorlesung 14 / Aufgabe 1 + * + * @author Sebastian Brosch + */ +class Aufgabe01 { + + public static void main(String[] args) { + Counter counterUp = new Counter("T1", 1, 100); + Counter counterDown = new Counter("T2", -10); + Thread threadCounterUp = new Thread(counterUp); + Thread threadCounterDown = new Thread(counterDown); + threadCounterUp.start(); + threadCounterDown.start(); + } +} diff --git a/VL14/Aufgabe01/Counter.java b/VL14/Aufgabe01/Counter.java new file mode 100644 index 0000000..a4bf283 --- /dev/null +++ b/VL14/Aufgabe01/Counter.java @@ -0,0 +1,56 @@ +package VL14.Aufgabe01; + +/** + * Class representing a counter. + * + * @author Sebastian Brosch + */ +public class Counter implements Runnable { + static int counter; + + // some information of the counter. + private int number; + private String name; + + /** + * Create a new counter with initializing the start value. + * + * @param name The name of the counter. + * @param number The number to increment or decrement the counter. + * @param start The start value of the counter. + */ + public Counter(String name, int number, int start) { + this(name, number); + counter = start; + } + + /** + * Create a new counter without initializing the start value. + * + * @param name The name of the counter. + * @param number The number to increment or decrement the counter. + */ + public Counter(String name, int number) { + this.number = number; + this.name = name; + } + + /** + * Method to run some code in a Thread. + */ + public void run() { + while (counter > 0 && counter < 1000) { + this.count(); + } + } + + /** + * Method to increment or decrement the counter. + */ + private void count() { + synchronized (getClass()) { + counter += this.number; + System.out.printf("%3d [%s: %3d]\n", counter, this.name, this.number); + } + } +}