added ex J

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

View File

@ -0,0 +1,33 @@
package exercises.ex_j;
class Diner {
private String name;
private boolean isHungry;
public Diner(String name) {
this.name = name;
isHungry = true;
}
public String getName() {
return name;
}
public boolean isHungry() {
return isHungry;
}
public void eatWith(Spoon spoon, Diner spouse) {
while (isHungry) {
if (spoon.getOwner() == this) {
if (spouse.isHungry()) {
System.out.println(getName() + ": You eat first my darling " + spouse.getName() + "!");
spoon.setOwner(spouse);
} else {
spoon.use();
this.isHungry = false;
}
}
}
}
}

View File

@ -0,0 +1,20 @@
package exercises.ex_j;
public class LivelockDinner {
public static void main(String[] args) {
final Diner husband = new Diner("Bob");
final Diner wife = new Diner("Alice");
final Spoon spoon = new Spoon(husband);
new Thread(new Runnable() {
public void run() {
husband.eatWith(spoon, wife);
}
}).start();
new Thread(new Runnable() {
public void run() {
wife.eatWith(spoon, husband);
}
}).start();
}
}

View File

@ -0,0 +1,21 @@
package exercises.ex_j;
class Spoon {
private Diner owner;
public synchronized Diner getOwner() {
return owner;
}
public Spoon(Diner d) {
owner = d;
}
public synchronized void setOwner(Diner d) {
owner = d;
}
public synchronized void use() {
System.out.printf("%s has eaten!", owner.getName());
}
}