Single Lane Bridge Problem | Oracle Java Combo
Problem : A single-lane bridge connects the two Vermont villages of North Tunbridge and South Tunbridge. Farmers in the two villages use this bridge to deliver their produce to the neighboring town. The bridge can become deadlocked if both a northbound and a southbound farmer get on the bridge at the same time (Vermont farmers are stubborn and are unable to back up.) Using semaphores, design an algorithm that prevents deadlock.
Use Lock or Semaphore
Read full article from Single Lane Bridge Problem | Oracle Java Combo
Problem : A single-lane bridge connects the two Vermont villages of North Tunbridge and South Tunbridge. Farmers in the two villages use this bridge to deliver their produce to the neighboring town. The bridge can become deadlocked if both a northbound and a southbound farmer get on the bridge at the same time (Vermont farmers are stubborn and are unable to back up.) Using semaphores, design an algorithm that prevents deadlock.
Use Lock or Semaphore
class
Bridge
{
private
final
Semaphore semaphore;
public
Bridge()
{
semaphore =
new
Semaphore(
1
);
}
public
void
crossBridge(Farmer farmer)
{
try
{
System.out.printf(
"Farmer %s is trying to cross the bridge.\n"
,farmer.getName());
semaphore.acquire();
System.out.printf(
"Farmer %s is crossing the bridge.\n"
,farmer.getName());
long
duration = (
long
)(Math.random() *
10
);
TimeUnit.SECONDS.sleep(duration);
}
catch
(InterruptedException iex)
{
iex.printStackTrace();
}
finally
{
System.out.printf(
"Farmer %s has crossed the bridge.\n"
,farmer.getName());
semaphore.release();
}
}
}