81.4k views
3 votes
A single-lane bridge connects village A to village B. Farmers in the two villages use this bridge to deliver their products to the neighboring town. The bridge can become deadlocked if a farmer from village A and a farmer from village B get on the bridge at the same time. Using semaphores and/or mutex locks (do not be concerned about starvation) implement your solution in Java. In particular, represent village A and village B farmers as separate threads. Once a farmer is on the bridge, the associated thread will sleep for a random period of time, representing traveling across the bridge.

1 Answer

4 votes

Answer:

Answer: Main Java

Step-by-step explanation:

code:

Main.java

import java.lang.InterruptedException;

import java.lang.Thread;

import java.util.Random;

public class Main {

final private static int FARMERS = 10;

public static void main(String[] args) {

Bridge bridge = new Bridge();

Random r = new Random();

System.out.println("Running with " + FARMERS + " farmers...");

// Enter a bunch of farmers from different directions.

for (int i = 0; i < FARMERS; i++) {

Farmer farmer;

if (r.nextBoolean()) {

farmer = new SouthBoundFarmer(bridge);

} else {

farmer = new NorthBoundFarmer(bridge);

}

cross(farmer);

}

}

private static void cross(Farmer f) {

new Thread(f).start();

}

}

SouthBoundFarmer.java

public class SouthBoundFarmer extends Farmer {

public SouthBoundFarmer(Bridge b) {

super(b);

this.name = "South";

}

}

Farmer.java

import java.lang.InterruptedException;

import java.util.Random;

public class Farmer implements Runnable {

private Bridge bridge;

private Random random;

protected String name;

public Farmer(Bridge b) {

this.bridge = b;

this.random = new Random();

}

public void crossBridge(Bridge bridge) {

System.out.println("[" + this.name + "] Waiting to enter bridge...");

try {

bridge.enter();

System.out.println("[" + this.name + "] Entering bridge...");

// Crossing bridge...some farmers are fast, others are slow :P

Thread.sleep(1000 + random.nextInt(9000));

System.out.println("[" + this.name + "] Leaving bridge...");

} catch (InterruptedException e) {

System.out.println("...Interrupted!");

} finally {

bridge.leave();

}

}

public void run() {

this.crossBridge(this.bridge);

}

}

User Marshalllaw
by
4.4k points