added ex I

This commit is contained in:
Louis Heredero 2024-12-10 13:26:07 +01:00
parent 43124b51cc
commit bd44a92834
Signed by: HEL
GPG Key ID: 8D83DE470F8544E7
2 changed files with 45 additions and 0 deletions

View File

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

View File

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