Vorlesung 14 / Aufgabe 2

This commit is contained in:
Sebastian Brosch 2024-05-30 11:27:24 +02:00
parent b96c8c7b21
commit c08f4d3196
4 changed files with 85 additions and 0 deletions

View File

@ -0,0 +1,27 @@
package VL14.Aufgabe02;
/**
* Vorlesung 14 / Aufgabe 2
*
* @author Sebastian Brosch
*/
public class Aufgabe02 {
public static void main(String[] args) {
final int NUMBER_OF_USERS = 5;
final int NUMBER_OF_PRINTERS = 2;
// create some users.
for (int u = 0; u < NUMBER_OF_USERS; u++) {
User user = new User();
Thread threadUser = new Thread(user);
threadUser.start();
}
// create some printers.
for (int p = 0; p < NUMBER_OF_PRINTERS; p++) {
Printer printer = new Printer();
Thread threadPrinter = new Thread(printer);
threadPrinter.start();
}
}
}

View File

@ -0,0 +1,23 @@
package VL14.Aufgabe02;
/**
* Class which represents a printer.
*
* @author Sebastian Brosch
*/
public class Printer implements Runnable {
public void run() {
while (true) {
synchronized (PrinterQueue.queue) {
if (PrinterQueue.queue.size() > 0) {
System.out.println(PrinterQueue.queue.poll());
}
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
}
}

View File

@ -0,0 +1,12 @@
package VL14.Aufgabe02;
import java.util.LinkedList;
/**
* Class which represents a printer queue.
*
* @author Sebastian Brosch
*/
public class PrinterQueue {
static LinkedList<String> queue = new LinkedList<String>();
}

23
VL14/Aufgabe02/User.java Normal file
View File

@ -0,0 +1,23 @@
package VL14.Aufgabe02;
/**
* Class which represents a user.
*
* @author Sebastian Brosch
*/
public class User implements Runnable {
private int number = 0;
public void run() {
while (true) {
synchronized (PrinterQueue.queue) {
PrinterQueue.queue.add(Thread.currentThread().getName() + ": " + this.number++);
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
}
}