added ex H2

This commit is contained in:
Louis Heredero 2024-12-10 14:57:33 +01:00
parent 237c35c6f7
commit b3a0d1f7a1
Signed by: HEL
GPG Key ID: 8D83DE470F8544E7
5 changed files with 95 additions and 0 deletions

View File

@ -0,0 +1,14 @@
package exercises.ex_h2;
public class Bridge {
private Road roadEast = new Road("East");
private Road roadWest = new Road("West");
public Road getRoadEast() {
return roadEast;
}
public Road getRoadWest() {
return roadWest;
}
}

View File

@ -0,0 +1,14 @@
package exercises.ex_h2;
public class Road {
private String position;
public Road(String position) {
this.position = position;
}
@Override
public String toString() {
return position + " road";
}
}

View File

@ -0,0 +1,13 @@
package exercises.ex_h2;
public class TestDeadlockBridge {
public static void main(String[] args) {
Bridge bridge = new Bridge();
//(new Thread(new Vehicle("Ferrari", bridge, bridge.getRoadEast()))).start();
//(new Thread(new Vehicle("BMW", bridge, bridge.getRoadWest()))).start();
// Version without DeadLock
(new Thread(new VehicleWithoutDeadlock("Ferrari", bridge, bridge.getRoadEast()))).start();
(new Thread(new VehicleWithoutDeadlock("BMW", bridge, bridge.getRoadWest()))).start();
}
}

View File

@ -0,0 +1,26 @@
package exercises.ex_h2;
public class Vehicle implements Runnable {
String name;
private Bridge bridge;
private Road road;
public Vehicle(String name, Bridge bridge, Road road) {
this.name = name;
this.bridge = bridge;
this.road = road;
}
@Override
public void run() {
// Do the actions to cross the bridge
synchronized (road) {
System.out.println(name + " is entering on the one-way bridge from " + road);
synchronized (road == bridge.getRoadEast() ?
bridge.getRoadWest():
bridge.getRoadEast()) {
System.out.println(name + " is leaving the one-way bridge");
}
}
}
}

View File

@ -0,0 +1,28 @@
package exercises.ex_h2;
public class VehicleWithoutDeadlock implements Runnable {
String name;
private Bridge bridge;
private Road road;
public VehicleWithoutDeadlock(String name, Bridge bridge, Road road) {
this.name = name;
this.bridge = bridge;
this.road = road;
}
@Override
public void run() {
// Do the actions to cross the bridge
synchronized (bridge) {
System.out.println(name + " is entering on the one-way bridge from " + road);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(name + " is leaving the one-way bridge");
}
}
}