added ex Q1

This commit is contained in:
Louis Heredero 2024-12-17 14:58:55 +01:00
parent 8374825610
commit 532a727b43
Signed by: HEL
GPG Key ID: 8D83DE470F8544E7
3 changed files with 73 additions and 0 deletions

View File

@ -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.");
}
}

View File

@ -0,0 +1,34 @@
package exercises.ex_q1;
import java.util.concurrent.Callable;
public class Pizzaiolo implements Callable<Pizza> {
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;
}
}

View File

@ -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<Pizza> future1 = executor.submit(marco);
Future<Pizza> future2 = executor.submit(antonio);
Future<Pizza> future3 = executor.submit(marco);
Future<Pizza> future4 = executor.submit(antonio);
marco.serve(future1.get());
antonio.serve(future2.get());
marco.serve(future3.get());
antonio.serve(future4.get());
executor.shutdown();
}
}