Parallel works as long as numUsers >= numPrinters

This commit is contained in:
Matti 2024-06-03 15:16:33 +02:00
parent eadcc6fe1c
commit b5d79e2b57
5 changed files with 61 additions and 32 deletions

View File

@ -38,6 +38,10 @@ public class Schlenglein <T>{
return this.maxSize;
}
public boolean isEmpty(){
return this.size()<=0;
}
public void attemptDynamicResize(){
if (numberOfElements < 0.2*maxSize){
// Kleiner Machen

View File

@ -9,11 +9,20 @@ Zwei Drucker stehen zur Verfügung und arbeiten die Aufträge ab.
Modellieren Sie das Problem als ErzeugerVerbraucherProblem und realisieren Sie es in Java.
*/
public class Demo {
public static void main(String[] args) {
User u1 = new User(1);
User u2 = new User(2);
u1.start();
u2.start();
int numUsers = 7;
int numPrinter = 4;
for (int i = 1; i <= numUsers; i++) {
User user = new User(i);
user.start();
}
for (int i = 1; i <= numPrinter ; i++) {
Printer printer = new Printer(i);
printer.start();
}
}
}

View File

@ -1,18 +1,31 @@
package part4.aufg2;
import part3.aufg2.Schlenglein;
public class Printer extends Thread {
private int threadNumber;
public class Printer {
static Schlenglein q;
public Printer(int threadNumber){
this.threadNumber = threadNumber;
}
public void run() {
synchronized (getClass()){
while (true) {
try {
q.wait();
synchronized (Puwwer.q) {
if (Puwwer.q.isEmpty()){
try {
Puwwer.q.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
System.out.println("Printer " + this.threadNumber + " prints " + Puwwer.q.get());
}
} catch (NullPointerException e){}
try {
sleep(100);
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
}
}
}

View File

@ -0,0 +1,7 @@
package part4.aufg2;
import part3.aufg2.Schlenglein;
public class Puwwer {
static Schlenglein q = new Schlenglein();
}

View File

@ -1,37 +1,33 @@
package part4.aufg2;
import part3.aufg2.Schlenglein;
public class User <T> extends Thread {
public class User extends Thread {
private int threadNumber;
static Schlenglein q = new Schlenglein<String>();
public User(int threadNumber) {
this.threadNumber = threadNumber;
}
public synchronized void makeRequest() {
synchronized (getClass()) {
synchronized (Puwwer.q) {
int randomInt = (int) (Math.random() * ((int) (Math.random() * 1000)));
String randomIntStr = this.threadNumber + " " + randomInt;
q.add(randomIntStr);
q.printAll();
Puwwer.q.add(randomIntStr);
System.out.println("User " + threadNumber + " added " + randomIntStr);
try {
Puwwer.q.notify();
} catch (IllegalMonitorStateException e) {
throw new RuntimeException(e);
}
}
}
public void run() {
try {
// q.notify();
} catch (IllegalMonitorStateException e) {
throw new RuntimeException(e);
}
for (int i = 0; i<10; i++) {
while (true) {
makeRequest();
try {
sleep(100);
sleep(3000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}