Question

In: Computer Science

Single Lane Bridge Problem : Java Threads Given : //Use ReentrantLock for mutual exclusion import java.util.concurrent.locks.Lock;...

Single Lane Bridge Problem : Java Threads

Given :

//Use ReentrantLock for mutual exclusion
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class bridge  {
    private final ReentrantLock myLock = new ReentrantLock();

    public bridge(){

    }

    public String cross(){
        myLock.lock();
        try {

            return "crossing the bridge";

        } finally {
            myLock.unlock();
        }
    }
}
public class lane extends Thread
{
    int cars;
    bridge Bridge;
    public lane(int Cars1, bridge Bridge1)
    {
        cars = Cars1;
        Bridge = Bridge1;
    }

    public void run(){
        for(int x=0;x

//Important clue :

<Thread-ID> waiting to cross

This means that this thread is now competing for the lock and will have to wait its turn.

- Once a thread has gained access to the critical section it should output:

<Thread-ID> crossing the bridge

- It takes different cars a different amount of time to cross the bridge, so your code should simulate this by sleeping for a random amount of time when accessing the critical section.

- Once a car has left the bridge, your program should output:

<Thread-ID> exiting

- Threads can enter the critical section in any order.

 

Create main such that the output is as follows :

Thread-0 waiting to cross

Thread-0 crossing the bridge

Thread-0 exiting

Thread-1 waiting to cross

Thread-2 waiting to cross

Thread-1 crossing the bridge

Thread-1 exiting

Thread-2 crossing the bridge

Thread-2 exiting

.....

.....

.....

.....

Solutions

Expert Solution

import java.util.concurrent.*;

// Defines a class SingleLaneBridgeDriver

public class SingleLaneBridgeDriver

{

// main method definition

public static void main(String[] ss)

{

// Creates an object of the class Bridge

final Bridge bridge = new Bridge();

  

// Defines an anonymous object for the class Thread

// for right to left lane

Thread laneRightToLeft = new Thread( new Runnable()

{

// Overrides the run() method

@Override

public void run()

{

// Loops infinitely

while(true)

{

// Creates an object of the class Car

Car currentCar = new Car(bridge);

  

// Creates a Thread for Car class object

Thread threadRL = new Thread(currentCar);

// Sets the name of the car to thread id

currentCar.setCarName("Thread: " + threadRL.getId());

// Calls the start() method to start the thread

threadRL.start();

  

// Try block for pause time

try

{

TimeUnit.SECONDS.sleep((long)(Math.random()*10));

}// End of try block

  

// Catch block to handle InterruptedException for sleep() method

catch(InterruptedException exp)

{

exp.printStackTrace();

}// End of catch

}// End of while loop

}// End of method

});// End of anonymous class

// Defines an anonymous object for the class Thread

// for right to left lane

Thread laneLeftToRight = new Thread( new Runnable()

{

// Overrides the run() method

@Override

public void run()

{

// Loops infinitely

while(true)

{

// Creates an object of the class Car

Car currentCar = new Car(bridge);

// Creates a Thread for Car class object

Thread threadLR = new Thread(currentCar);

// Sets the name of the car to thread id

currentCar.setCarName("Thread: " + threadLR.getId());

// Calls the start() method to start the thread

threadLR.start();

  

// Try block for pause time

try

{

TimeUnit.SECONDS.sleep((long)(Math.random()*10));

}// End of try block

  

// Catch block to handle InterruptedException for sleep() method

catch(InterruptedException exp)

{

exp.printStackTrace();

}// End of catch

}// End of while loop

}// End of method

});// End of anonymous class

  

// Calls the start method for both laneRightToLeft and

// laneLeftToRight

laneRightToLeft.start();

laneLeftToRight.start();

}// End of main method

}// End of driver class

// Defines class Bridge

class Bridge

{

// Declares an object of class Semaphore

private final Semaphore semaphore;

// Default constructor definition

public Bridge()

{

semaphore = new Semaphore(1);

}// End of constructor

  

// Method to implement mechanism of crossing bridge

public void crossBridge(Car newCar)

{

// try block begins

try

{

// Displays the name of the waiting car

System.out.printf("Car %s is waiting to cross the bridge.\n",

newCar.getCarName());

  

// Used to wait until a permit is not available

semaphore.acquire();

  

// Displays the name of the crossing car

System.out.printf("Car %s is crossing the bridge.\n",

newCar.getCarName());

// Calculates the time duration

long stopTime = (long)(Math.random() * 10);

// Sleeps for the duration of stopTime

TimeUnit.SECONDS.sleep(stopTime);

}// End of try block

  

// Catch block to handle InterruptedException for sleep() method

catch(InterruptedException exp)

{

exp.printStackTrace();

}// End of catch block

  

// finally block to display the crossed bridge car name

finally

{

System.out.printf("Car %s has crossed the bridge.\n",

newCar.getCarName());

semaphore.release();

}// End of finally block

}// End of method

}// End of class

// Defines a class Car which implements Runnable interface

class Car implements Runnable

{

// To store name of the car

private String carName;

// Declares an object of class bridge

private Bridge bridge;

  

// Parameterized constructor to assign parameter Bridge object to

// instance object

public Car(Bridge bri)

{

bridge = bri;

}// End of constructor

  

// Overrides the run() method of Runnable interface

public void run()

{

// Calls the method to cross the bridge

bridge.crossBridge(this);

}// End of method

// Method to return car name

public String getCarName()

{

return carName;

}// End of method

// Method to set the car name

public void setCarName(String name)

{

carName = name;

}// End of method

}// End of class Car

Sample Output:

Car Thread: 17 is waiting to cross the bridge.
Car Thread: 16 is waiting to cross the bridge.
Car Thread: 17 is crossing the bridge.
Car Thread: 18 is waiting to cross the bridge.
Car Thread: 17 has crossed the bridge.
Car Thread: 16 is crossing the bridge.
Car Thread: 16 has crossed the bridge.
Car Thread: 18 is crossing the bridge.
Car Thread: 19 is waiting to cross the bridge.
Car Thread: 20 is waiting to cross the bridge.
Car Thread: 18 has crossed the bridge.


Related Solutions

A single-lane bridge connects village A to village B. Farmers in the two villages use this...
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...
Question Four Explain Peterson’s solution for critical-section problem and show that mutual exclusion is preserved with...
Question Four Explain Peterson’s solution for critical-section problem and show that mutual exclusion is preserved with Peterson’s solution. (Assume there are only two processes P0 and P1)
JAVA ONLY - Complete the code import java.util.Scanner; /** * This program will use the HouseListing...
JAVA ONLY - Complete the code import java.util.Scanner; /** * This program will use the HouseListing class and display a list of * houses sorted by the house's listing number * * Complete the code below the numbered comments, 1 - 4. DO NOT CHANGE the * pre-written code * @author * */ public class HouseListingDemo { public static void main(String[] args) { Scanner scan = new Scanner(System.in); HouseListing[] list; String listNumber, listDesc; int count = 0; double listPrice; String...
Hi I have problem with run this JAVA file import java.io.*; public class DataPresenter { public...
Hi I have problem with run this JAVA file import java.io.*; public class DataPresenter { public static void main (String args []) { System.out.println("File:../SmallAreaIncomePovertyEstData.text"); System.out.println("Id" + "\t" + "Population" + "\t" + "ChildPop" + "\t" + "CPovPop" + "\t" + "CPovPop%"); }// read the data try (FileReader fr = new FileReader("File: C:\\605.201/SmallAreaIncomePovertyEstData.text")) { int c; while (( c = fr.read())!= -1){ System.out.print((char) c); } } catch(IOException e) { System.out.println("I/O Error" + e); }    } Please help to fix
Write a JAVA program that prompts the user to enter a single name. Use a for...
Write a JAVA program that prompts the user to enter a single name. Use a for loop to determine if the name entered by the user contains at least 1 uppercase and 3 lowercase letters. If the name meets this policy, output that the name has been accepted. Otherwise, output that the name is invalid.
Please provide the missng code(parts) for the given code in java. ASAP. import java.util.Stack; class StackQueue<T>...
Please provide the missng code(parts) for the given code in java. ASAP. import java.util.Stack; class StackQueue<T> implements Queue<T>{ private Stack<T> inStack; private Stack<T> outStack; private int size; public StackQueue(){ inStack = new Stack<T> (); outStack = PART(a); size = 0; } public int size(){ return size; } public boolean isEmpty(){ return size==0; } public T first(){ if (size == 0) return null;; if (outStack.empty()) while (!inStack.empty()) outStack.push(inStack.pop()); return PART(b); //return the element at the top of the outStack without removing...
Read the following problem. Use your knowledge about the Inclusion-Exclusion Principle to support your criteria. Telephone...
Read the following problem. Use your knowledge about the Inclusion-Exclusion Principle to support your criteria. Telephone numbering is an application of the inclusion-exclusion principle. Discuss with your peers a way in which the current telephone numbering plan can be extended to accommodate the rapid demand for more telephone numbers. (See if you can find some of the proposals coming from the telecommunications industry). For each new numbering plan you discuss show how to find the number of different telephone numbers...
Use the data below to solve the following problem using excel: 1 a) Import the data...
Use the data below to solve the following problem using excel: 1 a) Import the data into an Excel file. Done! b) Create a new column in the spreadsheet to assign the category of each car according to the engine horsepower. For this exercise use IF statements in each cell to determine the class for each vehicle. i. Class 1 if the vehicle horsepower is less than 80 HP. ii. Class 2 if the vehicle horsepower is between 81 and...
Use if statements to write a Java program that inputs a single letter and prints out...
Use if statements to write a Java program that inputs a single letter and prints out the corresponding digit on the telephone. The letters and digits on a telephone are grouped this way: 2 = ABC    3 = DEF   4 = GHI    5 = JKL 6 = MNO   7 = PRS   8 = TUV 9 = WXY No digit corresponds to either Q or Z. For these 2 letters your program should print a message indicating that they are not...
Problem 10A-8 Applying Overhead; Overhead Variances [LO10-3, LO10-4] Lane Company manufactures a single product that requires...
Problem 10A-8 Applying Overhead; Overhead Variances [LO10-3, LO10-4] Lane Company manufactures a single product that requires a great deal of hand labor. Overhead cost is applied on the basis of standard direct labor-hours. The budgeted variable manufacturing overhead is $2 per direct labor-hour and the budgeted fixed manufacturing overhead is $480,000 per year. The standard quantity of materials is 3 pounds per unit and the standard cost is $7 per pound. The standard direct labor-hours per unit is 1.5 hours...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT