From 532a727b43be25a5cfa9dfd06d2d20a183b3384e Mon Sep 17 00:00:00 2001 From: LordBaryhobal Date: Tue, 17 Dec 2024 14:58:55 +0100 Subject: [PATCH] added ex Q1 --- src/exercises/ex_q1/Pizza.java | 13 ++++++++++++ src/exercises/ex_q1/Pizzaiolo.java | 34 ++++++++++++++++++++++++++++++ src/exercises/ex_q1/Pizzeria.java | 26 +++++++++++++++++++++++ 3 files changed, 73 insertions(+) create mode 100644 src/exercises/ex_q1/Pizza.java create mode 100644 src/exercises/ex_q1/Pizzaiolo.java create mode 100644 src/exercises/ex_q1/Pizzeria.java diff --git a/src/exercises/ex_q1/Pizza.java b/src/exercises/ex_q1/Pizza.java new file mode 100644 index 0000000..93f9885 --- /dev/null +++ b/src/exercises/ex_q1/Pizza.java @@ -0,0 +1,13 @@ +package exercises.ex_q1; + +public class Pizza { + public void prepare() { + System.out.println("Preparing pizza."); + } + public void bake() { + System.out.println("Baking pizza."); + } + public void cut() { + System.out.println("Cutting pizza."); + } +} diff --git a/src/exercises/ex_q1/Pizzaiolo.java b/src/exercises/ex_q1/Pizzaiolo.java new file mode 100644 index 0000000..138fd97 --- /dev/null +++ b/src/exercises/ex_q1/Pizzaiolo.java @@ -0,0 +1,34 @@ +package exercises.ex_q1; + +import java.util.concurrent.Callable; + +public class Pizzaiolo implements Callable { + private final String name; + + public Pizzaiolo(String name) { + this.name = name; + } + + public void serve(Pizza pizza) { + System.out.println(name + "'s pizza is ready: pizza " + pizza.hashCode()); + } + + public Pizza makePizza() throws InterruptedException { + Pizza pizza = new Pizza(); + pizza.prepare(); + Thread.sleep(200); + pizza.bake(); + Thread.sleep(300); + pizza.cut(); + Thread.sleep(100); + return pizza; + } + + @Override + public Pizza call() throws Exception { + System.out.println("Thread " + name + " started by the executor"); + Pizza pizza = makePizza(); + System.out.println("Thread " + name + " pizza finished"); + return pizza; + } +} diff --git a/src/exercises/ex_q1/Pizzeria.java b/src/exercises/ex_q1/Pizzeria.java new file mode 100644 index 0000000..04fb085 --- /dev/null +++ b/src/exercises/ex_q1/Pizzeria.java @@ -0,0 +1,26 @@ +package exercises.ex_q1; + +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.ScheduledExecutorService; + +public class Pizzeria { + public static void main(String[] args) throws ExecutionException, InterruptedException { + ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); + Pizzaiolo marco = new Pizzaiolo("Marco"); + Pizzaiolo antonio = new Pizzaiolo("Antonio"); + + Future future1 = executor.submit(marco); + Future future2 = executor.submit(antonio); + Future future3 = executor.submit(marco); + Future future4 = executor.submit(antonio); + + marco.serve(future1.get()); + antonio.serve(future2.get()); + marco.serve(future3.get()); + antonio.serve(future4.get()); + + executor.shutdown(); + } +}