Created
February 2, 2025 01:22
-
-
Save aerodame/af2ea6d30c7c540f3e88ed0e87356be5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class Worker extends Thread { | |
| private final Semaphore semaphore; | |
| ConcurrentHashMap<Integer, String> sharedCalculatedFactorials; | |
| public Worker(String name, Semaphore semaphore, ConcurrentHashMap<Integer, String> factorialsHashMap) { | |
| super(name); | |
| this.semaphore = semaphore; | |
| this.sharedCalculatedFactorials = factorialsHashMap; | |
| } | |
| @Override | |
| public void run() { | |
| Process process = new Process(getName()); // Use the simulated Process class | |
| Random random = new Random(); | |
| try { | |
| Thread.sleep(random.nextInt(1000)); | |
| semaphore.P(process); // Acquire the semaphore and queue the process if wait needed | |
| // Critical Section | |
| process.criticalSection(sharedCalculatedFactorials); | |
| semaphore.V(); | |
| // Remainder Section | |
| Thread.sleep(random.nextInt(2000)); // Remainder section delay (0-1999 ms) | |
| } catch (InterruptedException e) { | |
| e.printStackTrace(); | |
| } finally { | |
| System.out.println(process.getName() + ": Terminating"); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment