added ex K

This commit is contained in:
Louis Heredero 2024-12-10 15:35:35 +01:00
parent a1bfa6021a
commit 3c6d89bdd8
Signed by: HEL
GPG Key ID: 8D83DE470F8544E7
5 changed files with 117 additions and 0 deletions

View File

@ -0,0 +1,31 @@
package exercises.ex_k;
public class Customer implements Runnable {
private String name;
private PostOffice postOffice;
public Customer(String name, PostOffice postOffice) {
this.name = name;
this.postOffice = postOffice;
}
public String getName() {
return name;
}
@Override
public void run() {
Package pkg;
while (true) {
pkg = new Package(this);
System.out.println("Registering " + pkg + "...");
postOffice.registerPackage(pkg);
System.out.println("Registered " + pkg);
try {
Thread.sleep((long) (Math.random() * 2000 + 1000));
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}

View File

@ -0,0 +1,15 @@
package exercises.ex_k;
public class Package {
private Customer sender;
public Package(Customer sender) {
this.sender = sender;
}
@Override
public String toString() {
return "Package{" +
"sender=" + sender.getName() +
'}';
}
}

View File

@ -0,0 +1,38 @@
package exercises.ex_k;
import java.util.LinkedList;
import java.util.List;
public class PostOffice {
public static final int CAPACITY = 5;
private List<Package> packages = new LinkedList<>();
public synchronized void registerPackage(Package pkg) {
while (packages.size() >= CAPACITY) {
try {
System.out.println("[PostOffice] Storage is full, waiting");
wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
packages.add(pkg);
System.out.println("[PostOffice] Storage: " + packages.size() + " / " + CAPACITY);
notifyAll();
}
public synchronized Package getNextPackage() {
while (packages.isEmpty()) {
try {
System.out.println("[PostOffice] Storage is empty, waiting");
wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
Package pkg = packages.removeFirst();
System.out.println("[PostOffice] Storage: " + packages.size() + " / " + CAPACITY);
notifyAll();
return pkg;
}
}

View File

@ -0,0 +1,23 @@
package exercises.ex_k;
public class Postman implements Runnable {
private PostOffice postOffice;
public Postman(PostOffice postOffice) {
this.postOffice = postOffice;
}
@Override
public void run() {
Package pkg;
while (true) {
pkg = postOffice.getNextPackage();
System.out.println("Delivering " + pkg);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}

View File

@ -0,0 +1,10 @@
package exercises.ex_k;
public class TestingGuardedBlocks {
public static void main(String[] args) {
PostOffice postOffice = new PostOffice();
(new Thread(new Postman(postOffice))).start();
(new Thread(new Customer("Mrs Darbellay", postOffice))).start();
(new Thread(new Customer("Mrs Müller", postOffice))).start();
}
}