Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Project 4-2 You will write a Java program that uses synchronization techniques t

ID: 3724204 • Letter: P

Question

Project 4-2 You will write a Java program that uses synchronization techniques to simulate traffic from two directions crossing a one-lane bridge. Java program that uses either semaphores or Java synchronization to control access Assignment: Write a multithreaded to a one-lane bridge. One thread should simulate southbound vehicles and another thread should simulate northbound vehicles. The vehicles do not have a reverse gear, so the bridge would become deadlocked if both a southbound vehicle and a northbound vehicle were allowed to drive onto the bridge at the same time. Therefore, mutual exclusion must be enforced. Your solution should avoid both deadlock and starvation (e.g. the bridge being monopolized by southbound vehicles while the northbound vehicles never get to cross). Vehicles traveling in either direction should wait (sleep) for some amount of time, then attempt to cross. Once a vehicle is on the bridge, it should sleep for some amount of time to simulate how long it takes to drive across the bridge. Output a message when each vehicle drives onto the bridge and another message when that vehicle has completed the crossing. Simulate several vehicles traveling in each direction

Explanation / Answer

import java.util.concurrent.*;

class MyThread extends Thread

{

Semaphore sem;

String threadName;

public MyThread(Semaphore sem, String threadName)

{

super(threadName);

this.sem = sem;

this.threadName = threadName;

}

  

public void run() {

try

{

Thread.sleep(500); // Starvation is handled

System.out.println("A "+ threadName + " vehicle is attempting to cross the bridge");

// First, get a permit.

System.out.println("A "+ threadName + " vehicle is waiting for a permit.");

// acquiring the lock

sem.acquire();

System.out.println("A "+ threadName + " vehicle gets a permit.");

// Now, accessing the shared resource bridge.

// other waiting threads will wait, until this

// thread release the lock

System.out.println("A "+ threadName + " vehicle is passing through bridge");

Thread.sleep(100);

System.out.println("A "+ threadName + " vehicle passed through bridge");   

} catch (InterruptedException exc) {

System.out.println(exc);

}

// Release the permit.

System.out.println("A "+ threadName + " vehicle releases the permit.");

sem.release();

  

}

}

public class BridgeController
{
public static void main(String args[]) throws InterruptedException
{
// creating a Semaphore object
// with number of permits 1
Semaphore sem = new Semaphore(1);


MyThread mt1 = new MyThread(sem, "NorthBound");
MyThread mt2 = new MyThread(sem, "SouthBound");

  
mt1.start();
mt2.start();

  
mt1.join();
mt2.join();

  
}
}