From a1bfa6021a08250a304e6bdeb55ca7946f454bf5 Mon Sep 17 00:00:00 2001 From: LordBaryhobal Date: Tue, 10 Dec 2024 15:17:19 +0100 Subject: [PATCH] added ex J --- src/exercises/ex_j/Diner.java | 33 ++++++++++++++++++++++++++ src/exercises/ex_j/LivelockDinner.java | 20 ++++++++++++++++ src/exercises/ex_j/Spoon.java | 21 ++++++++++++++++ 3 files changed, 74 insertions(+) create mode 100644 src/exercises/ex_j/Diner.java create mode 100644 src/exercises/ex_j/LivelockDinner.java create mode 100644 src/exercises/ex_j/Spoon.java diff --git a/src/exercises/ex_j/Diner.java b/src/exercises/ex_j/Diner.java new file mode 100644 index 0000000..969f68d --- /dev/null +++ b/src/exercises/ex_j/Diner.java @@ -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; + } + } + } + } +} diff --git a/src/exercises/ex_j/LivelockDinner.java b/src/exercises/ex_j/LivelockDinner.java new file mode 100644 index 0000000..8872684 --- /dev/null +++ b/src/exercises/ex_j/LivelockDinner.java @@ -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(); + } +} diff --git a/src/exercises/ex_j/Spoon.java b/src/exercises/ex_j/Spoon.java new file mode 100644 index 0000000..e019712 --- /dev/null +++ b/src/exercises/ex_j/Spoon.java @@ -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()); + } +}