SlideShare ist ein Scribd-Unternehmen logo
1 von 6
Downloaden Sie, um offline zu lesen
Create a PostalWorkerThread class that extends Thread, which will serve the customers in line.
The PostalWorkerThread class will need to acquire the postalWorkerMutex semaphore to enter
the critical section where it can interact with the customer threads. Once a postal worker thread
finishes serving a customer, it should release the postalWorkerMutex semaphore. You also need
to ensure that only one postal worker can use the scales at a time. Currently, my code creates a
semaphore for scalesMutex, but it is not being used in the code. You should also add print
statements to my code to match the output format mentioned in the project description.
My code:
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
import java.util.concurrent.Semaphore;
public class PostOfficeSimulation {
// Constants
private static final int MAX_CUSTOMERS = 50;
private static final int MAX_CUSTOMERS_INSIDE = 10;
private static final int MAX_POSTAL_WORKERS = 3;
// Semaphores
private static Semaphore customerMutex = new Semaphore(1);
private static Semaphore postalWorkerMutex = new Semaphore(1);
private static Semaphore scalesMutex = new Semaphore(1);
private static Semaphore customersInside = new Semaphore(MAX_CUSTOMERS_INSIDE);
private static Semaphore postalWorkersAvailable = new
Semaphore(MAX_POSTAL_WORKERS);
// Task Table
private static final int BUY_STAMPS_TIME = 60;
private static final int MAIL_LETTER_TIME = 90;
private static final int MAIL_PACKAGE_TIME = 120;
// Random number generator
private static Random random = new Random();
// Customer thread
private static class CustomerThread extends Thread {
private int id;
private int task;
private Semaphore semaphore;
public CustomerThread(int id) {
this.id = id;
this.task = random.nextInt(3);
this.semaphore = new Semaphore(0);
}
public void run() {
try {
System.out.printf("Customer %d createdn", id);
customersInside.acquire();
System.out.printf("Customer %d enters post officen", id);
Thread.sleep(1000 * getTaskTime() / 60);
System.out.printf("Customer %d asks postal worker to %sn", id, getTaskName());
postalWorkerMutex.acquire();
postalWorkersAvailable.acquire();
System.out.printf("Postal worker %d serving customer %dn", getPostalWorkerId(),
id);
scalesMutex.acquire();
Thread.sleep(1000 * getTaskTime() / 60);
scalesMutex.release();
System.out.printf("Postal worker %d finished serving customer %dn",
getPostalWorkerId(), id);
postalWorkersAvailable.release();
postalWorkerMutex.release();
Thread.sleep(1000);
System.out.printf("Customer %d finished %sn", id, getTaskName());
System.out.printf("Customer %d leaves post officen", id);
customersInside.release();
semaphore.release();
System.out.printf("Joined customer %dn", id);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private int getTaskTime() {
switch (task) {
case 0:
return BUY_STAMPS_TIME;
case 1:
return MAIL_LETTER_TIME;
case 2:
return MAIL_PACKAGE_TIME;
default:
return 0;
}
}
private String getTaskName() {
switch (task) {
case 0:
return "buy stamps";
case 1:
return "mail a letter";
case 2:
return "mail a package";
default:
return "";
}
}
private int getPostalWorkerId() {
return id % MAX_POSTAL_WORKERS;
}
public void releaseSemaphore() {
semaphore.release();
}
}
// Postal worker thread
private static class PostalWorkerThread extends Thread {
private int id;
public PostalWorkerThread(int id) {
// Postal worker thread
private static class PostalWorkerThread extends Thread {
private int id;
public PostalWorkerThread(int id) {
this.id = id;
}
@Override
public void run() {
System.out.printf("Postal worker %d createdn", id);
while (true) {
try {
// Wait for a customer to arrive
customersInside.acquire();
customerMutex.acquire();
// Serve the customer
System.out.printf("Postal worker %d serving customer %dn", id,
Main.customerQueue.peek().id);
switch (Main.customerQueue.peek().task) {
case 0:
Thread.sleep(BUY_STAMPS_TIME * 1000);
System.out.printf("Customer %d finished buying stampsn",
Main.customerQueue.peek().id);
break;
case 1:
Thread.sleep(MAIL_LETTER_TIME * 1000);
System.out.printf("Customer %d finished mailing a lettern",
Main.customerQueue.peek().id);
break;
case 2:
scalesMutex.acquire();
System.out.println("Scales in use by postal worker " + id);
Thread.sleep(MAIL_PACKAGE_TIME * 1000);
System.out.printf("Customer %d finished mailing a packagen",
Main.customerQueue.peek().id);
scalesMutex.release();
break;
}
Main.customerQueue.poll().releaseSemaphore();
// Release resources
customerMutex.release();
customersInside.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
// Main class
public static class Main {
public static Semaphore customerSemaphore = new Semaphore(0);
public static Queue customerQueue = new LinkedList<>();
public static void main(String[] args) {
System.out.println("Simulating Post Office with 50 customers and 3 postal workers");
// Start postal worker threads
for (int i = 0; i < MAX_POSTAL_WORKERS; i++) {
new PostalWorkerThread(i).start();
}
// Start customer threads
for (int i = 0; i < MAX_CUSTOMERS; i++) {
CustomerThread customerThread = new CustomerThread(i);
customerThread.start();
try {
Thread.sleep(random.nextInt(500) + 500); // Sleep for 0.5-1.0 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// Join all customer threads
for (int i = 0; i < MAX_CUSTOMERS; i++) {
try {
customerSemaphore.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// Print joined messages
for (int i = 0; i < MAX_CUSTOMERS; i++) {
System.out.printf("Joined customer %dn", i);
}
}
}
}

Weitere ähnliche Inhalte

Ähnlich wie Create a PostalWorkerThread class that extends Thread, which will se.pdf

- the modification will be done in Main class- first, asks the use.pdf
- the modification will be done in Main class- first, asks the use.pdf- the modification will be done in Main class- first, asks the use.pdf
- the modification will be done in Main class- first, asks the use.pdf
hanumanparsadhsr
 
The java program that prompts user to enter a string and .pdf
  The java program that prompts user to  enter a string and .pdf  The java program that prompts user to  enter a string and .pdf
The java program that prompts user to enter a string and .pdf
DEEPAKSONI562
 
Architecting JavaScript Code
Architecting JavaScript CodeArchitecting JavaScript Code
Architecting JavaScript Code
Suresh Balla
 
Should be in JavaInterface Worker should extend Serializable from .pdf
Should be in JavaInterface Worker should extend Serializable from .pdfShould be in JavaInterface Worker should extend Serializable from .pdf
Should be in JavaInterface Worker should extend Serializable from .pdf
fashionscollect
 
Going towards inversion of control and better design
Going towards inversion of control and better designGoing towards inversion of control and better design
Going towards inversion of control and better design
oazabir
 

Ähnlich wie Create a PostalWorkerThread class that extends Thread, which will se.pdf (20)

Testing in android
Testing in androidTesting in android
Testing in android
 
- the modification will be done in Main class- first, asks the use.pdf
- the modification will be done in Main class- first, asks the use.pdf- the modification will be done in Main class- first, asks the use.pdf
- the modification will be done in Main class- first, asks the use.pdf
 
Ensure code quality with vs2012
Ensure code quality with vs2012Ensure code quality with vs2012
Ensure code quality with vs2012
 
Creation vsm modelos componentes electronicos
Creation vsm   modelos componentes electronicosCreation vsm   modelos componentes electronicos
Creation vsm modelos componentes electronicos
 
JavaExamples
JavaExamplesJavaExamples
JavaExamples
 
The java program that prompts user to enter a string and .pdf
  The java program that prompts user to  enter a string and .pdf  The java program that prompts user to  enter a string and .pdf
The java program that prompts user to enter a string and .pdf
 
Bt0087 wml and wap programing2
Bt0087 wml and wap programing2Bt0087 wml and wap programing2
Bt0087 wml and wap programing2
 
Architecting JavaScript Code
Architecting JavaScript CodeArchitecting JavaScript Code
Architecting JavaScript Code
 
Dart for Java Developers
Dart for Java DevelopersDart for Java Developers
Dart for Java Developers
 
ajax_pdf
ajax_pdfajax_pdf
ajax_pdf
 
ajax_pdf
ajax_pdfajax_pdf
ajax_pdf
 
Java concurrency model - The Future Task
Java concurrency model - The Future TaskJava concurrency model - The Future Task
Java concurrency model - The Future Task
 
Daggerate your code - Write your own annotation processor
Daggerate your code - Write your own annotation processorDaggerate your code - Write your own annotation processor
Daggerate your code - Write your own annotation processor
 
Wicket 6
Wicket 6Wicket 6
Wicket 6
 
#3 (Multi Threads With TCP)
#3 (Multi Threads With TCP)#3 (Multi Threads With TCP)
#3 (Multi Threads With TCP)
 
Build Widgets
Build WidgetsBuild Widgets
Build Widgets
 
Should be in JavaInterface Worker should extend Serializable from .pdf
Should be in JavaInterface Worker should extend Serializable from .pdfShould be in JavaInterface Worker should extend Serializable from .pdf
Should be in JavaInterface Worker should extend Serializable from .pdf
 
Going towards inversion of control and better design
Going towards inversion of control and better designGoing towards inversion of control and better design
Going towards inversion of control and better design
 
4Developers: Dominik Przybysz- Message Brokers
4Developers: Dominik Przybysz- Message Brokers4Developers: Dominik Przybysz- Message Brokers
4Developers: Dominik Przybysz- Message Brokers
 
Creating a Whatsapp Clone - Part II.pdf
Creating a Whatsapp Clone - Part II.pdfCreating a Whatsapp Clone - Part II.pdf
Creating a Whatsapp Clone - Part II.pdf
 

Mehr von ameerandsons

cultura y diversidad 1. Paralenguaje se refiere a a. Contacto vi.pdf
cultura y diversidad 1. Paralenguaje se refiere a a. Contacto vi.pdfcultura y diversidad 1. Paralenguaje se refiere a a. Contacto vi.pdf
cultura y diversidad 1. Paralenguaje se refiere a a. Contacto vi.pdf
ameerandsons
 
Cuando una encuesta mide el compromiso de los empleados de una organ.pdf
Cuando una encuesta mide el compromiso de los empleados de una organ.pdfCuando una encuesta mide el compromiso de los empleados de una organ.pdf
Cuando una encuesta mide el compromiso de los empleados de una organ.pdf
ameerandsons
 
Cuenta Saldo 31122013 Saldo 31122014 Depreciaci�n acumulada $2.pdf
Cuenta Saldo 31122013 Saldo 31122014 Depreciaci�n acumulada $2.pdfCuenta Saldo 31122013 Saldo 31122014 Depreciaci�n acumulada $2.pdf
Cuenta Saldo 31122013 Saldo 31122014 Depreciaci�n acumulada $2.pdf
ameerandsons
 
Cuando el suministro es de inter�s p�blico Roche y Tamiflu El caso .pdf
Cuando el suministro es de inter�s p�blico Roche y Tamiflu El caso .pdfCuando el suministro es de inter�s p�blico Roche y Tamiflu El caso .pdf
Cuando el suministro es de inter�s p�blico Roche y Tamiflu El caso .pdf
ameerandsons
 
CS520 Computer Architecture Project 2 � Spring 2023 Due date 0326.pdf
CS520 Computer Architecture Project 2 � Spring 2023 Due date 0326.pdfCS520 Computer Architecture Project 2 � Spring 2023 Due date 0326.pdf
CS520 Computer Architecture Project 2 � Spring 2023 Due date 0326.pdf
ameerandsons
 

Mehr von ameerandsons (20)

Culturas de mercado A) Empoderar a los empleados para que asuman .pdf
Culturas de mercado A) Empoderar a los empleados para que asuman .pdfCulturas de mercado A) Empoderar a los empleados para que asuman .pdf
Culturas de mercado A) Empoderar a los empleados para que asuman .pdf
 
Current Event #2 - summarize a recent business article from a source.pdf
Current Event #2 - summarize a recent business article from a source.pdfCurrent Event #2 - summarize a recent business article from a source.pdf
Current Event #2 - summarize a recent business article from a source.pdf
 
cultura y diversidad 1. Paralenguaje se refiere a a. Contacto vi.pdf
cultura y diversidad 1. Paralenguaje se refiere a a. Contacto vi.pdfcultura y diversidad 1. Paralenguaje se refiere a a. Contacto vi.pdf
cultura y diversidad 1. Paralenguaje se refiere a a. Contacto vi.pdf
 
Cryptography13.Consider the following matrix with entries from E,.pdf
Cryptography13.Consider the following matrix with entries from E,.pdfCryptography13.Consider the following matrix with entries from E,.pdf
Cryptography13.Consider the following matrix with entries from E,.pdf
 
Cuatro tendencias principales que afectan el comercio mundial a prin.pdf
Cuatro tendencias principales que afectan el comercio mundial a prin.pdfCuatro tendencias principales que afectan el comercio mundial a prin.pdf
Cuatro tendencias principales que afectan el comercio mundial a prin.pdf
 
Cuando una encuesta mide el compromiso de los empleados de una organ.pdf
Cuando una encuesta mide el compromiso de los empleados de una organ.pdfCuando una encuesta mide el compromiso de los empleados de una organ.pdf
Cuando una encuesta mide el compromiso de los empleados de una organ.pdf
 
Cuenta Saldo 31122013 Saldo 31122014 Depreciaci�n acumulada $2.pdf
Cuenta Saldo 31122013 Saldo 31122014 Depreciaci�n acumulada $2.pdfCuenta Saldo 31122013 Saldo 31122014 Depreciaci�n acumulada $2.pdf
Cuenta Saldo 31122013 Saldo 31122014 Depreciaci�n acumulada $2.pdf
 
Cuando una empresa instala filiales que producen algunos de los insu.pdf
Cuando una empresa instala filiales que producen algunos de los insu.pdfCuando una empresa instala filiales que producen algunos de los insu.pdf
Cuando una empresa instala filiales que producen algunos de los insu.pdf
 
Cuando un proceso no est� bajo control que significa No est� haci.pdf
Cuando un proceso no est� bajo control que significa No est� haci.pdfCuando un proceso no est� bajo control que significa No est� haci.pdf
Cuando un proceso no est� bajo control que significa No est� haci.pdf
 
Cuando un proyectil (una roca del espacio, digamos) golpea la superf.pdf
Cuando un proyectil (una roca del espacio, digamos) golpea la superf.pdfCuando un proyectil (una roca del espacio, digamos) golpea la superf.pdf
Cuando un proyectil (una roca del espacio, digamos) golpea la superf.pdf
 
Cuando se trata de evaluaciones de desempe�o, los supervisores y los.pdf
Cuando se trata de evaluaciones de desempe�o, los supervisores y los.pdfCuando se trata de evaluaciones de desempe�o, los supervisores y los.pdf
Cuando se trata de evaluaciones de desempe�o, los supervisores y los.pdf
 
Cuando los lobos regresaron por primera vez a Yellowstone, las pobla.pdf
Cuando los lobos regresaron por primera vez a Yellowstone, las pobla.pdfCuando los lobos regresaron por primera vez a Yellowstone, las pobla.pdf
Cuando los lobos regresaron por primera vez a Yellowstone, las pobla.pdf
 
Cuando Joe maximiza la utilidad, encuentra que su MRS de X por Y (o .pdf
Cuando Joe maximiza la utilidad, encuentra que su MRS de X por Y (o .pdfCuando Joe maximiza la utilidad, encuentra que su MRS de X por Y (o .pdf
Cuando Joe maximiza la utilidad, encuentra que su MRS de X por Y (o .pdf
 
Cuando el suministro es de inter�s p�blico Roche y Tamiflu El caso .pdf
Cuando el suministro es de inter�s p�blico Roche y Tamiflu El caso .pdfCuando el suministro es de inter�s p�blico Roche y Tamiflu El caso .pdf
Cuando el suministro es de inter�s p�blico Roche y Tamiflu El caso .pdf
 
Cuando escuchas la palabra liderazgo, �qu� te viene a la mente Co.pdf
Cuando escuchas la palabra liderazgo, �qu� te viene a la mente Co.pdfCuando escuchas la palabra liderazgo, �qu� te viene a la mente Co.pdf
Cuando escuchas la palabra liderazgo, �qu� te viene a la mente Co.pdf
 
Cuando el fago lambda de tipo salvaje se sembra en placas en un c�sp.pdf
Cuando el fago lambda de tipo salvaje se sembra en placas en un c�sp.pdfCuando el fago lambda de tipo salvaje se sembra en placas en un c�sp.pdf
Cuando el fago lambda de tipo salvaje se sembra en placas en un c�sp.pdf
 
Cualquier ayuda es bienvenida. Jayne Butterfield, una madre solter.pdf
Cualquier ayuda es bienvenida. Jayne Butterfield, una madre solter.pdfCualquier ayuda es bienvenida. Jayne Butterfield, una madre solter.pdf
Cualquier ayuda es bienvenida. Jayne Butterfield, una madre solter.pdf
 
CS520 Computer Architecture Project 2 � Spring 2023 Due date 0326.pdf
CS520 Computer Architecture Project 2 � Spring 2023 Due date 0326.pdfCS520 Computer Architecture Project 2 � Spring 2023 Due date 0326.pdf
CS520 Computer Architecture Project 2 � Spring 2023 Due date 0326.pdf
 
Cross-cultural industrial and organizational psychology. Citation Tr.pdf
Cross-cultural industrial and organizational psychology. Citation Tr.pdfCross-cultural industrial and organizational psychology. Citation Tr.pdf
Cross-cultural industrial and organizational psychology. Citation Tr.pdf
 
Cryptography is designed to turn information into a format that is d.pdf
Cryptography is designed to turn information into a format that is d.pdfCryptography is designed to turn information into a format that is d.pdf
Cryptography is designed to turn information into a format that is d.pdf
 

Kürzlich hochgeladen

Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 

Kürzlich hochgeladen (20)

Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 

Create a PostalWorkerThread class that extends Thread, which will se.pdf

  • 1. Create a PostalWorkerThread class that extends Thread, which will serve the customers in line. The PostalWorkerThread class will need to acquire the postalWorkerMutex semaphore to enter the critical section where it can interact with the customer threads. Once a postal worker thread finishes serving a customer, it should release the postalWorkerMutex semaphore. You also need to ensure that only one postal worker can use the scales at a time. Currently, my code creates a semaphore for scalesMutex, but it is not being used in the code. You should also add print statements to my code to match the output format mentioned in the project description. My code: import java.util.LinkedList; import java.util.Queue; import java.util.Random; import java.util.concurrent.Semaphore; public class PostOfficeSimulation { // Constants private static final int MAX_CUSTOMERS = 50; private static final int MAX_CUSTOMERS_INSIDE = 10; private static final int MAX_POSTAL_WORKERS = 3; // Semaphores private static Semaphore customerMutex = new Semaphore(1); private static Semaphore postalWorkerMutex = new Semaphore(1); private static Semaphore scalesMutex = new Semaphore(1); private static Semaphore customersInside = new Semaphore(MAX_CUSTOMERS_INSIDE); private static Semaphore postalWorkersAvailable = new Semaphore(MAX_POSTAL_WORKERS); // Task Table private static final int BUY_STAMPS_TIME = 60; private static final int MAIL_LETTER_TIME = 90; private static final int MAIL_PACKAGE_TIME = 120; // Random number generator private static Random random = new Random(); // Customer thread private static class CustomerThread extends Thread { private int id;
  • 2. private int task; private Semaphore semaphore; public CustomerThread(int id) { this.id = id; this.task = random.nextInt(3); this.semaphore = new Semaphore(0); } public void run() { try { System.out.printf("Customer %d createdn", id); customersInside.acquire(); System.out.printf("Customer %d enters post officen", id); Thread.sleep(1000 * getTaskTime() / 60); System.out.printf("Customer %d asks postal worker to %sn", id, getTaskName()); postalWorkerMutex.acquire(); postalWorkersAvailable.acquire(); System.out.printf("Postal worker %d serving customer %dn", getPostalWorkerId(), id); scalesMutex.acquire(); Thread.sleep(1000 * getTaskTime() / 60); scalesMutex.release(); System.out.printf("Postal worker %d finished serving customer %dn", getPostalWorkerId(), id); postalWorkersAvailable.release(); postalWorkerMutex.release(); Thread.sleep(1000); System.out.printf("Customer %d finished %sn", id, getTaskName()); System.out.printf("Customer %d leaves post officen", id); customersInside.release(); semaphore.release(); System.out.printf("Joined customer %dn", id); } catch (InterruptedException e) { e.printStackTrace(); } } private int getTaskTime() {
  • 3. switch (task) { case 0: return BUY_STAMPS_TIME; case 1: return MAIL_LETTER_TIME; case 2: return MAIL_PACKAGE_TIME; default: return 0; } } private String getTaskName() { switch (task) { case 0: return "buy stamps"; case 1: return "mail a letter"; case 2: return "mail a package"; default: return ""; } } private int getPostalWorkerId() { return id % MAX_POSTAL_WORKERS; } public void releaseSemaphore() { semaphore.release(); } } // Postal worker thread private static class PostalWorkerThread extends Thread { private int id; public PostalWorkerThread(int id) { // Postal worker thread
  • 4. private static class PostalWorkerThread extends Thread { private int id; public PostalWorkerThread(int id) { this.id = id; } @Override public void run() { System.out.printf("Postal worker %d createdn", id); while (true) { try { // Wait for a customer to arrive customersInside.acquire(); customerMutex.acquire(); // Serve the customer System.out.printf("Postal worker %d serving customer %dn", id, Main.customerQueue.peek().id); switch (Main.customerQueue.peek().task) { case 0: Thread.sleep(BUY_STAMPS_TIME * 1000); System.out.printf("Customer %d finished buying stampsn", Main.customerQueue.peek().id); break; case 1: Thread.sleep(MAIL_LETTER_TIME * 1000); System.out.printf("Customer %d finished mailing a lettern", Main.customerQueue.peek().id); break; case 2: scalesMutex.acquire(); System.out.println("Scales in use by postal worker " + id); Thread.sleep(MAIL_PACKAGE_TIME * 1000); System.out.printf("Customer %d finished mailing a packagen", Main.customerQueue.peek().id);
  • 5. scalesMutex.release(); break; } Main.customerQueue.poll().releaseSemaphore(); // Release resources customerMutex.release(); customersInside.release(); } catch (InterruptedException e) { e.printStackTrace(); } } } } // Main class public static class Main { public static Semaphore customerSemaphore = new Semaphore(0); public static Queue customerQueue = new LinkedList<>(); public static void main(String[] args) { System.out.println("Simulating Post Office with 50 customers and 3 postal workers"); // Start postal worker threads for (int i = 0; i < MAX_POSTAL_WORKERS; i++) { new PostalWorkerThread(i).start(); } // Start customer threads for (int i = 0; i < MAX_CUSTOMERS; i++) { CustomerThread customerThread = new CustomerThread(i); customerThread.start(); try { Thread.sleep(random.nextInt(500) + 500); // Sleep for 0.5-1.0 seconds } catch (InterruptedException e) { e.printStackTrace();
  • 6. } } // Join all customer threads for (int i = 0; i < MAX_CUSTOMERS; i++) { try { customerSemaphore.acquire(); } catch (InterruptedException e) { e.printStackTrace(); } } // Print joined messages for (int i = 0; i < MAX_CUSTOMERS; i++) { System.out.printf("Joined customer %dn", i); } } } }