Skip to content

Instantly share code, notes, and snippets.

@aerodame
Created February 2, 2025 01:22
Show Gist options
  • Save aerodame/af2ea6d30c7c540f3e88ed0e87356be5 to your computer and use it in GitHub Desktop.
Save aerodame/af2ea6d30c7c540f3e88ed0e87356be5 to your computer and use it in GitHub Desktop.
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