added ex R

This commit is contained in:
Louis Heredero 2025-01-06 15:18:17 +01:00
parent 53add330f4
commit a7216b1642
Signed by: HEL
GPG Key ID: 8D83DE470F8544E7
5 changed files with 94 additions and 0 deletions

View File

@ -0,0 +1,28 @@
package exercises.ex_r;
public class Customer implements Runnable {
private String name;
private PostOffice office;
public Customer(String name, PostOffice office) {
this.name = name;
this.office = office;
}
public String getName() {
return name;
}
@Override
public void run() {
while (true) {
Package pkg = new Package(this);
office.registerPackage(pkg);
try {
Thread.sleep((long) (1000L + 5000L * Math.random()));
} catch (InterruptedException e) {
break;
}
}
}
}

View File

@ -0,0 +1,15 @@
package exercises.ex_r;
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,19 @@
package exercises.ex_r;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class PostOffice {
private BlockingQueue<Package> packages = new LinkedBlockingQueue<>();
public void registerPackage(Package pkg) {
packages.add(pkg);
System.out.println("Registered " + pkg + " (now " + packages.size() + ")");
}
public Package takePackage() throws InterruptedException {
Package pkg = packages.take();
System.out.println("Withdrawn " + pkg + " (now " + packages.size() + ")");
return pkg;
}
}

View File

@ -0,0 +1,22 @@
package exercises.ex_r;
public class Postman implements Runnable {
private PostOffice office;
public Postman(PostOffice office) {
this.office = office;
}
@Override
public void run() {
while (true) {
try {
Package pkg = office.takePackage();
Thread.sleep((long) (1000L + 2000L * Math.random()));
System.out.println("Delivered " + pkg);
} catch (InterruptedException e) {
break;
}
}
}
}

View File

@ -0,0 +1,10 @@
package exercises.ex_r;
public class TestingBlockingQueue_PostOffice {
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();
}
}