From bd44a92834b26c0c1b483d63a1006a86121a94b2 Mon Sep 17 00:00:00 2001 From: LordBaryhobal Date: Tue, 10 Dec 2024 13:26:07 +0100 Subject: [PATCH] added ex I --- src/exercicses/ex_i/Employee.java | 32 ++++++++++++++++++++++ src/exercicses/ex_i/TestingStarvation.java | 13 +++++++++ 2 files changed, 45 insertions(+) create mode 100644 src/exercicses/ex_i/Employee.java create mode 100644 src/exercicses/ex_i/TestingStarvation.java diff --git a/src/exercicses/ex_i/Employee.java b/src/exercicses/ex_i/Employee.java new file mode 100644 index 0000000..03c9d3b --- /dev/null +++ b/src/exercicses/ex_i/Employee.java @@ -0,0 +1,32 @@ +package exercicses.ex_i; + +public class Employee extends Thread { + private String name; + private String room; + private int exageratedTimeUsageFactor; + + public Employee(String name, String room, int exageratedTimeUsageFactor) { + this.name = name; + this.room = room; + this.exageratedTimeUsageFactor = exageratedTimeUsageFactor; + } + + public void useRoom(int time) { + synchronized (room) { + System.out.println(name + " uses room for time: " + time); + try { + Thread.sleep(time); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } + } + + @Override + public void run() { + System.out.println(name + " thread started"); + while (true) { + useRoom(100 * exageratedTimeUsageFactor); + } + } +} diff --git a/src/exercicses/ex_i/TestingStarvation.java b/src/exercicses/ex_i/TestingStarvation.java new file mode 100644 index 0000000..0019fae --- /dev/null +++ b/src/exercicses/ex_i/TestingStarvation.java @@ -0,0 +1,13 @@ +package exercicses.ex_i; + +public class TestingStarvation { + public static void main(String[] args) { + String sharedRoom = "Polaris"; + Employee t1 = new Employee("Emma", sharedRoom, 1); + Employee t2 = new Employee("Jean", sharedRoom, 100); + + t1.start(); + t2.start(); + System.out.println("Main thread ended"); + } +}