Skip to content

Instantly share code, notes, and snippets.

@aerodame
Last active February 3, 2025 02:08
Show Gist options
  • Save aerodame/15b4ab89f89cd6f72330c76e8398413b to your computer and use it in GitHub Desktop.
Save aerodame/15b4ab89f89cd6f72330c76e8398413b to your computer and use it in GitHub Desktop.
import java.util.Random;
public class App {
public static void main(String[] args) {
ResourceAllocator allocator = new ResourceAllocator();
// Example usage with multiple "Processes"
Runnable P0 = ( ) -> {
... // same code, different critical section time = 1000
};
Runnable P1 = () -> {
... // same code, different critical section time = 1000
};
Runnable P2 = () -> {
Random random = new Random();
int entry_delay=1000; int time_out=2000; int cs_time=4000; int exit_delay=2000;
try {
Thread.sleep(random.nextInt(entry_delay)); // Random process entry delay
allocator.acquire(time_out); // Wait at most 2 seconds
Thread.sleep(cs_time); // Simulate critical section
allocator.release();
Thread.sleep(random.nextInt(exit_delay)); // Random process exit delay
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
};
Thread p0 = new Thread(P0, "Process 0"); Thread p1 = new Thread(P1, "Process 1");
Thread p2 = new Thread(P2, "Process 2");
p0.start(); p1.start(); p2.start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment