Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Random;
- import java.util.concurrent.Semaphore;
- class Demo {
- public static void main(String[] args) throws InterruptedException {
- DiningPhilosophers.runTest();
- }
- }
- public class DiningPhilosophers {
- private static Random random = new Random(System.currentTimeMillis());
- private Semaphore[] forks = new Semaphore[5];
- public DiningPhilosophers() {
- forks[0] = new Semaphore(1);
- forks[1] = new Semaphore(1);
- forks[2] = new Semaphore(1);
- forks[3] = new Semaphore(1);
- forks[4] = new Semaphore(1);
- }
- public void lifecycleOfPhilosopher(int id) throws InterruptedException {
- while (true) {
- think(id);
- eat(id);
- }
- }
- void think(int id) throws InterruptedException {
- System.out.println(String.format("Philosopher %d is thinking.", id));
- Thread.sleep(random.nextInt(50));
- }
- void eat(int id) throws InterruptedException {
- // TODO: 3/29/20 Synchronize
- int leftIndex = id;
- int rightIndex = (id!=0)? id-1 : 4;
- System.out.println(String.format("Philosopher %d trying to pick up left fork.", id));
- forks[leftIndex].acquire();
- System.out.println(String.format("Philosopher %d picked up left fork.", id));
- System.out.println(String.format("Philosopher %d trying to pick up right fork.", id));
- if (forks[rightIndex].tryAcquire()) {
- System.out.println(String.format("Philosopher %d picked up right fork.", id));
- eating(id);
- System.out.println(String.format("Philosopher %d putting down right fork", id));
- forks[rightIndex].release();
- }
- System.out.println(String.format("Philosopher %d putting down left fork", id));
- forks[id].release();
- }
- private void eating(int id) throws InterruptedException {
- System.out.println(String.format("Philosopher %d is eating", id));
- Thread.sleep(random.nextInt(50));
- }
- static void runPhilosopher(DiningPhilosophers dp, int id) {
- try {
- dp.lifecycleOfPhilosopher(id);
- } catch (InterruptedException ie) {
- }
- }
- public static void runTest() throws InterruptedException {
- final DiningPhilosophers dp = new DiningPhilosophers();
- Thread p1 = new Thread(new Runnable() {
- public void run() {
- runPhilosopher(dp, 0);
- }
- });
- Thread p2 = new Thread(new Runnable() {
- public void run() {
- runPhilosopher(dp, 1);
- }
- });
- Thread p3 = new Thread(new Runnable() {
- public void run() {
- runPhilosopher(dp, 2);
- }
- });
- Thread p4 = new Thread(new Runnable() {
- public void run() {
- runPhilosopher(dp, 3);
- }
- });
- Thread p5 = new Thread(new Runnable() {
- public void run() {
- runPhilosopher(dp, 4);
- }
- });
- p1.start();
- p2.start();
- p3.start();
- p4.start();
- p5.start();
- p1.join();
- p2.join();
- p3.join();
- p4.join();
- p5.join();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement