now using wait and notify

This commit is contained in:
Sebastian Brosch 2024-06-03 22:04:50 +02:00
parent 108cd3259e
commit b90a013f4c
4 changed files with 44 additions and 11 deletions

View File

@ -1,5 +1,7 @@
package VL14.Aufgabe02;
import java.util.Random;
/**
* Vorlesung 14 / Aufgabe 2
*
@ -7,12 +9,12 @@ package VL14.Aufgabe02;
*/
public class Aufgabe02 {
public static void main(String[] args) {
final int NUMBER_OF_USERS = 5;
final int NUMBER_OF_USERS = 10;
final int NUMBER_OF_PRINTERS = 2;
// create some users.
for (int u = 0; u < NUMBER_OF_USERS; u++) {
User user = new User();
User user = new User(getRandomNumber(1, 10) * 1000);
Thread threadUser = new Thread(user);
threadUser.start();
}
@ -24,4 +26,15 @@ public class Aufgabe02 {
threadPrinter.start();
}
}
/**
* Method to determine a random number from a certain range.
*
* @param start The first number of the range.
* @param end The last number of the range.
* @return A random number from a certain range.
*/
private static int getRandomNumber(int start, int end) {
return (new Random()).nextInt((end - start + 1)) + start;
}
}

View File

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

View File

@ -8,5 +8,5 @@ import java.util.LinkedList;
* @author Sebastian Brosch
*/
public class PrinterQueue {
static LinkedList<String> queue = new LinkedList<String>();
static LinkedList<Integer> queue = new LinkedList<Integer>();
}

View File

@ -7,15 +7,35 @@ package VL14.Aufgabe02;
*/
public class User implements Runnable {
private int number = 0;
private int wait = 0;
/**
* Constructor to initialize a User.
*/
public User() {
this.wait = 1000;
}
/**
* Constructor to initialize a User.
*
* @param wait The time the user is waiting for creating new print jobs.
*/
public User(int wait) {
this.wait = wait;
}
public void run() {
while (true) {
synchronized (PrinterQueue.queue) {
PrinterQueue.queue.add(Thread.currentThread().getName() + ": " + this.number++);
int data = this.number++;
PrinterQueue.queue.add(data);
System.out.println("User " + Thread.currentThread().threadId() + " adds: " + data);
PrinterQueue.queue.notifyAll();
}
try {
Thread.sleep(100);
Thread.sleep(this.wait);
} catch (InterruptedException e) {
}
}