Uebungsaufgaben/Semester2/Vorlesung3.java
2024-06-03 21:59:58 +02:00

45 lines
956 B
Java

package Semester2;
import java.lang.Thread;
public class Vorlesung3 extends Thread{
static int sharedvar = 5;
boolean updown;
int howmuch;
public Vorlesung3(boolean updown, int howmuch, String name) {
this.updown = updown;
this.howmuch = howmuch;
this.setName(name);
}
public static void main(String[] args) {
Vorlesung3 zaehler1 = new Vorlesung3(true, 1, "Thread1");
zaehler1.start();
Vorlesung3 zaehler2 = new Vorlesung3(false, 1, "Thread2");
zaehler2.start();
}
public void run() {
while (sharedvar != 0) {
berechnung(this.updown, this.howmuch);
System.out.println(this.getName() + ": " + sharedvar);
}
}
public static synchronized void berechnung(boolean updown, int howmuch) {
if (updown) {
sharedvar += howmuch;
} else {
sharedvar -= howmuch;
}
}
}