75 lines
2.1 KiB
Java
75 lines
2.1 KiB
Java
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();
|
|
}
|
|
}
|
|
}
|
|
}
|