Vorlesung 14 / Aufgabe 1
This commit is contained in:
parent
c08f4d3196
commit
dad420e8d8
18
VL14/Aufgabe01/Aufgabe01.java
Normal file
18
VL14/Aufgabe01/Aufgabe01.java
Normal file
@ -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();
|
||||
}
|
||||
}
|
56
VL14/Aufgabe01/Counter.java
Normal file
56
VL14/Aufgabe01/Counter.java
Normal file
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user