SlideShare a Scribd company logo
1 of 7
Download to read offline
Assignment: Write a multithreaded Java program that uses either semaphores or Java
synchronization to control access to a one-lane bridge. One thread should simulate eastbound
vehicles and another thread should simulate westbound vehicles. The vehicles do not have a
reverse gear, so the bridge would become deadlocked if both an eastbound vehicle and a
westbound 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 westbound vehicles while the eastbound 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.
Solution
public class baboon{
public static boolean eastLock = false;
public static boolean westLock = false;
public static int onBranch = 0;
public static void main(String [] args)
{
BaboonEast bEast = new BaboonEast();
BaboonWest bWest = new BaboonWest();
for (int i=1; i<=10; i++)
{
new Thread(bEast, "E: "+i).start();
new Thread(bWest, "W: "+i).start();
//bEast.start();
}//for
}//main
}//class
class BaboonEast extends Thread
{
public void run()
{
while (baboon.westLock == true)
{
System.out.println(Thread.currentThread().getName() + "
waiting");
try
{
sleep(50);
} catch (InterruptedException ex) {}
}//while
//baboon.eastLock = true; //stops west baboons entering
baboon.onBranch ++;
baboon.westLock = true;
baboon.eastLock = true;
System.out.println("Baboon " + Thread.currentThread().getName() + " is
entering");
try
{
sleep(100);
} catch (InterruptedException ex) {}
baboon.onBranch --;
System.out.println ("Baboon " + Thread.currentThread().getName() + "
has crossed");
if (baboon.onBranch <= 0)
{
baboon.eastLock = false;
baboon.westLock = false;
}
//System.out.println(baboon.onBranch);
}//run
}//class
class BaboonWest extends Thread
{
public void run()
{
while (baboon.eastLock == true)
{
System.out.println(Thread.currentThread().getName() + "
waiting");
try
{
sleep(50);
} catch (InterruptedException ex) {}
}//while
baboon.westLock = true; //stops east baboons entering
baboon.onBranch ++;
System.out.println("Baboon " + Thread.currentThread().getName() + " is
entering");
baboon.westLock = true;
baboon.eastLock = true;
try
{
sleep(100);
} catch (InterruptedException ex) {}
baboon.onBranch --;
System.out.println ("Baboon " + Thread.currentThread().getName() + "
has crossed");
if (baboon.onBranch <= 0)
{
baboon.westLock = false;
baboon.eastLock = false;
}
//System.out.println(baboon.onBranch);
}//run
}//class

More Related Content

More from amritashinfosalys

Choose the one that the correct sequence (going from Mart to finish) .pdf
Choose the one that the correct sequence (going from Mart to finish) .pdfChoose the one that the correct sequence (going from Mart to finish) .pdf
Choose the one that the correct sequence (going from Mart to finish) .pdf
amritashinfosalys
 
what are the five major activities of an operating system in regard .pdf
what are the five major activities of an operating system in regard .pdfwhat are the five major activities of an operating system in regard .pdf
what are the five major activities of an operating system in regard .pdf
amritashinfosalys
 
What are the key components of a typical centralized all-air HVAC sys.pdf
What are the key components of a typical centralized all-air HVAC sys.pdfWhat are the key components of a typical centralized all-air HVAC sys.pdf
What are the key components of a typical centralized all-air HVAC sys.pdf
amritashinfosalys
 
Useful addition rules for mutually exclusive eventsRule 1 Given .pdf
Useful addition rules for mutually exclusive eventsRule 1 Given .pdfUseful addition rules for mutually exclusive eventsRule 1 Given .pdf
Useful addition rules for mutually exclusive eventsRule 1 Given .pdf
amritashinfosalys
 
This if for a C# assignment.Please explain a scenariouse case for.pdf
This if for a C# assignment.Please explain a scenariouse case for.pdfThis if for a C# assignment.Please explain a scenariouse case for.pdf
This if for a C# assignment.Please explain a scenariouse case for.pdf
amritashinfosalys
 
The Hubble law shows the relationship between the mass of a galaxy a.pdf
The Hubble law shows the relationship between the mass of a galaxy a.pdfThe Hubble law shows the relationship between the mass of a galaxy a.pdf
The Hubble law shows the relationship between the mass of a galaxy a.pdf
amritashinfosalys
 
1) What does globalization mean2) Is globalization a good thi.pdf
1) What does globalization mean2) Is globalization a good thi.pdf1) What does globalization mean2) Is globalization a good thi.pdf
1) What does globalization mean2) Is globalization a good thi.pdf
amritashinfosalys
 

More from amritashinfosalys (20)

Each of the following is a function of membranes except sites for spe.pdf
Each of the following is a function of membranes except sites for spe.pdfEach of the following is a function of membranes except sites for spe.pdf
Each of the following is a function of membranes except sites for spe.pdf
 
Develop a detailed Compliance budget for fiscal year 2015-16 for a 1.pdf
Develop a detailed Compliance budget for fiscal year 2015-16 for a 1.pdfDevelop a detailed Compliance budget for fiscal year 2015-16 for a 1.pdf
Develop a detailed Compliance budget for fiscal year 2015-16 for a 1.pdf
 
Devlin Inc produces snack foods such as bagel chips. The company had .pdf
Devlin Inc produces snack foods such as bagel chips. The company had .pdfDevlin Inc produces snack foods such as bagel chips. The company had .pdf
Devlin Inc produces snack foods such as bagel chips. The company had .pdf
 
Choose the one that the correct sequence (going from Mart to finish) .pdf
Choose the one that the correct sequence (going from Mart to finish) .pdfChoose the one that the correct sequence (going from Mart to finish) .pdf
Choose the one that the correct sequence (going from Mart to finish) .pdf
 
Connecting the Concepts Structural Adaptations in Land Plants What .pdf
Connecting the Concepts Structural Adaptations in Land Plants  What .pdfConnecting the Concepts Structural Adaptations in Land Plants  What .pdf
Connecting the Concepts Structural Adaptations in Land Plants What .pdf
 
Business statistics1.How is the trend eliminated in the ratio-to-m.pdf
Business statistics1.How is the trend eliminated in the ratio-to-m.pdfBusiness statistics1.How is the trend eliminated in the ratio-to-m.pdf
Business statistics1.How is the trend eliminated in the ratio-to-m.pdf
 
At the end of Meiosis I for this organism, what is the policy number .pdf
At the end of Meiosis I for this organism, what is the policy number .pdfAt the end of Meiosis I for this organism, what is the policy number .pdf
At the end of Meiosis I for this organism, what is the policy number .pdf
 
African and white abolitionist often did not get along whySoluti.pdf
African and white abolitionist often did not get along whySoluti.pdfAfrican and white abolitionist often did not get along whySoluti.pdf
African and white abolitionist often did not get along whySoluti.pdf
 
What unique properties of the genome do forensic scientists use to g.pdf
What unique properties of the genome do forensic scientists use to g.pdfWhat unique properties of the genome do forensic scientists use to g.pdf
What unique properties of the genome do forensic scientists use to g.pdf
 
what are the five major activities of an operating system in regard .pdf
what are the five major activities of an operating system in regard .pdfwhat are the five major activities of an operating system in regard .pdf
what are the five major activities of an operating system in regard .pdf
 
What are the key components of a typical centralized all-air HVAC sys.pdf
What are the key components of a typical centralized all-air HVAC sys.pdfWhat are the key components of a typical centralized all-air HVAC sys.pdf
What are the key components of a typical centralized all-air HVAC sys.pdf
 
What are lymphoid nodules and where are they located What functions.pdf
What are lymphoid nodules and where are they located What functions.pdfWhat are lymphoid nodules and where are they located What functions.pdf
What are lymphoid nodules and where are they located What functions.pdf
 
Useful addition rules for mutually exclusive eventsRule 1 Given .pdf
Useful addition rules for mutually exclusive eventsRule 1 Given .pdfUseful addition rules for mutually exclusive eventsRule 1 Given .pdf
Useful addition rules for mutually exclusive eventsRule 1 Given .pdf
 
There are three possible fates for immature B cells with IgM that re.pdf
There are three possible fates for immature B cells with IgM that re.pdfThere are three possible fates for immature B cells with IgM that re.pdf
There are three possible fates for immature B cells with IgM that re.pdf
 
This if for a C# assignment.Please explain a scenariouse case for.pdf
This if for a C# assignment.Please explain a scenariouse case for.pdfThis if for a C# assignment.Please explain a scenariouse case for.pdf
This if for a C# assignment.Please explain a scenariouse case for.pdf
 
The Hubble law shows the relationship between the mass of a galaxy a.pdf
The Hubble law shows the relationship between the mass of a galaxy a.pdfThe Hubble law shows the relationship between the mass of a galaxy a.pdf
The Hubble law shows the relationship between the mass of a galaxy a.pdf
 
The difference between the saturated dissolved oxygen concentration .pdf
The difference between the saturated dissolved oxygen concentration .pdfThe difference between the saturated dissolved oxygen concentration .pdf
The difference between the saturated dissolved oxygen concentration .pdf
 
1) What does globalization mean2) Is globalization a good thi.pdf
1) What does globalization mean2) Is globalization a good thi.pdf1) What does globalization mean2) Is globalization a good thi.pdf
1) What does globalization mean2) Is globalization a good thi.pdf
 
SNR calculation for conventional AM small noise case Prove that sign.pdf
SNR calculation for conventional AM small noise case Prove that sign.pdfSNR calculation for conventional AM small noise case Prove that sign.pdf
SNR calculation for conventional AM small noise case Prove that sign.pdf
 
Question 6 Of the following, which one is not a component of the proj.pdf
Question 6 Of the following, which one is not a component of the proj.pdfQuestion 6 Of the following, which one is not a component of the proj.pdf
Question 6 Of the following, which one is not a component of the proj.pdf
 

Recently uploaded

SPLICE Working Group: Reusable Code Examples
SPLICE Working Group:Reusable Code ExamplesSPLICE Working Group:Reusable Code Examples
SPLICE Working Group: Reusable Code Examples
Peter Brusilovsky
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
AnaAcapella
 

Recently uploaded (20)

Including Mental Health Support in Project Delivery, 14 May.pdf
Including Mental Health Support in Project Delivery, 14 May.pdfIncluding Mental Health Support in Project Delivery, 14 May.pdf
Including Mental Health Support in Project Delivery, 14 May.pdf
 
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
 
SPLICE Working Group: Reusable Code Examples
SPLICE Working Group:Reusable Code ExamplesSPLICE Working Group:Reusable Code Examples
SPLICE Working Group: Reusable Code Examples
 
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptxAnalyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
 
VAMOS CUIDAR DO NOSSO PLANETA! .
VAMOS CUIDAR DO NOSSO PLANETA!                    .VAMOS CUIDAR DO NOSSO PLANETA!                    .
VAMOS CUIDAR DO NOSSO PLANETA! .
 
MOOD STABLIZERS DRUGS.pptx
MOOD     STABLIZERS           DRUGS.pptxMOOD     STABLIZERS           DRUGS.pptx
MOOD STABLIZERS DRUGS.pptx
 
Trauma-Informed Leadership - Five Practical Principles
Trauma-Informed Leadership - Five Practical PrinciplesTrauma-Informed Leadership - Five Practical Principles
Trauma-Informed Leadership - Five Practical Principles
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
The Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDFThe Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDF
 
Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...
 
Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community PartnershipsSpring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
 
Observing-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxObserving-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptx
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
 
How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17
 
ANTI PARKISON DRUGS.pptx
ANTI         PARKISON          DRUGS.pptxANTI         PARKISON          DRUGS.pptx
ANTI PARKISON DRUGS.pptx
 
Basic Civil Engineering notes on Transportation Engineering & Modes of Transport
Basic Civil Engineering notes on Transportation Engineering & Modes of TransportBasic Civil Engineering notes on Transportation Engineering & Modes of Transport
Basic Civil Engineering notes on Transportation Engineering & Modes of Transport
 
An Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge AppAn Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge App
 

Assignment Write a multithreaded Java program that uses either semap.pdf

  • 1. Assignment: Write a multithreaded Java program that uses either semaphores or Java synchronization to control access to a one-lane bridge. One thread should simulate eastbound vehicles and another thread should simulate westbound vehicles. The vehicles do not have a reverse gear, so the bridge would become deadlocked if both an eastbound vehicle and a westbound 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 westbound vehicles while the eastbound 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. Solution public class baboon{ public static boolean eastLock = false; public static boolean westLock = false; public static int onBranch = 0; public static void main(String [] args) { BaboonEast bEast = new BaboonEast(); BaboonWest bWest = new BaboonWest();
  • 2. for (int i=1; i<=10; i++) { new Thread(bEast, "E: "+i).start(); new Thread(bWest, "W: "+i).start(); //bEast.start(); }//for }//main }//class class BaboonEast extends Thread { public void run() { while (baboon.westLock == true)
  • 3. { System.out.println(Thread.currentThread().getName() + " waiting"); try { sleep(50); } catch (InterruptedException ex) {} }//while //baboon.eastLock = true; //stops west baboons entering baboon.onBranch ++; baboon.westLock = true; baboon.eastLock = true; System.out.println("Baboon " + Thread.currentThread().getName() + " is entering"); try { sleep(100); } catch (InterruptedException ex) {}
  • 4. baboon.onBranch --; System.out.println ("Baboon " + Thread.currentThread().getName() + " has crossed"); if (baboon.onBranch <= 0) { baboon.eastLock = false; baboon.westLock = false; } //System.out.println(baboon.onBranch); }//run }//class
  • 5. class BaboonWest extends Thread { public void run() { while (baboon.eastLock == true) { System.out.println(Thread.currentThread().getName() + " waiting"); try { sleep(50); } catch (InterruptedException ex) {} }//while baboon.westLock = true; //stops east baboons entering baboon.onBranch ++; System.out.println("Baboon " + Thread.currentThread().getName() + " is entering"); baboon.westLock = true;
  • 6. baboon.eastLock = true; try { sleep(100); } catch (InterruptedException ex) {} baboon.onBranch --; System.out.println ("Baboon " + Thread.currentThread().getName() + " has crossed"); if (baboon.onBranch <= 0) { baboon.westLock = false; baboon.eastLock = false; }