some changes from practice group

This commit is contained in:
Sebastian Brosch 2024-06-10 15:20:28 +02:00
parent e1eaf252de
commit 1f0c7abff6
4 changed files with 21 additions and 32 deletions

View File

@ -8,23 +8,21 @@ import java.util.Random;
* @author Sebastian Brosch
*/
public class Aufgabe02 {
public static void main(String[] args) {
final int NUMBER_OF_USERS = 10;
public static void main(String[] args) throws Exception {
final int NUMBER_OF_USERS = 2;
final int NUMBER_OF_PRINTERS = 2;
// create some users.
for (int u = 0; u < NUMBER_OF_USERS; u++) {
User user = new User(getRandomNumber(1, 10) * 1000);
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);
Thread threadPrinter = new Thread(new Printer());
threadPrinter.start();
}
// create some users.
for (int u = 0; u < NUMBER_OF_USERS; u++) {
Thread threadUser = new Thread(new User(getRandomNumber(1, 10) * 1000));
threadUser.start();
}
}
/**

View File

@ -10,12 +10,8 @@ public class Printer implements Runnable {
while (true) {
synchronized (PrinterQueue.queue) {
if (PrinterQueue.queue.size() > 0) {
System.out.println("Printer " + Thread.currentThread().threadId() + " prints: " + PrinterQueue.queue.poll());
} else {
try {
PrinterQueue.queue.wait();
} catch (InterruptedException e) {
}
System.out.println("Printer " + Thread.currentThread().threadId() + " prints: " + PrinterQueue.queue.getFirst());
PrinterQueue.queue.removeFirst();
}
}
}

View File

@ -1,6 +1,8 @@
package VL14.Aufgabe02;
import java.util.LinkedList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Class which represents a printer queue.
@ -8,5 +10,5 @@ import java.util.LinkedList;
* @author Sebastian Brosch
*/
public class PrinterQueue {
static LinkedList<Integer> queue = new LinkedList<Integer>();
static List<Object> queue = Collections.synchronizedList(new ArrayList<>());
}

View File

@ -7,7 +7,7 @@ package VL14.Aufgabe02;
*/
public class User implements Runnable {
private int number = 0;
private int wait = 0;
private long wait = 0;
/**
* Constructor to initialize a User.
@ -26,18 +26,11 @@ public class User implements Runnable {
}
public void run() {
while (true) {
synchronized (PrinterQueue.queue) {
while (this.wait > 0) {
int data = this.number++;
PrinterQueue.queue.add(data);
System.out.println("User " + Thread.currentThread().threadId() + " adds: " + data);
PrinterQueue.queue.notifyAll();
}
try {
Thread.sleep(this.wait);
} catch (InterruptedException e) {
}
System.out.println("User " + Thread.currentThread().threadId() + " added " + data);
this.wait--;
}
}
}