Aufgaben Vorlesung 3

This commit is contained in:
cmerkens 2024-06-03 21:59:58 +02:00
parent 89897bf745
commit 555aefdf26
2 changed files with 118 additions and 0 deletions

44
Semester2/Vorlesung3.java Normal file
View File

@ -0,0 +1,44 @@
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;
}
}
}

View File

@ -0,0 +1,74 @@
package Semester2;
import java.util.LinkedList;
import java.util.Queue;
public class Vorlesung3part2 extends Thread{
static Queue<Integer> queue = new LinkedList<>();
boolean wasBinIch;
public Vorlesung3part2(boolean wasBinIch, String name) {
this.wasBinIch = wasBinIch;
this.setName(name);
}
public static void main(String[] args) {
Vorlesung3part2 erzeuger1 = new Vorlesung3part2(true, "Hugo");
erzeuger1.start();
Vorlesung3part2 erzeuger2 = new Vorlesung3part2(true, "Dieter");
erzeuger2.start();
Vorlesung3part2 erzeuger3 = new Vorlesung3part2(true, "Kai");
erzeuger3.start();
Vorlesung3part2 verbraucher1 = new Vorlesung3part2(false, "D1");
verbraucher1.start();
Vorlesung3part2 verbraucher2 = new Vorlesung3part2(false, "D2");
verbraucher2.start();
}
public void run() {
if (this.wasBinIch) {
this.erzeuger();
} else {
this.verbraucher();
}
}
public void erzeuger() {
while (true) {
try {
Thread.sleep((int) (Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (queue) {
queue.add(1);
System.out.println(this.getName() + " hat Druckauftrag hinzugefügt");
System.out.println(queue + "\n");
queue.notify();
}
}
}
public void verbraucher() {
while (true) {
synchronized (queue) {
while (queue.isEmpty()) {
try {
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
queue.remove();
System.out.println(this.getName() + " hat einen Druckauftrag abgearbeitet");
}
try {
Thread.sleep((int) (Math.random() * 900));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}