File tree Expand file tree Collapse file tree
core-java/src/main/java/com/baeldung/concurrent/diningphilosophers Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package com .baeldung .concurrent .diningphilosophers ;
2+
3+ public class DiningPhilosophers {
4+
5+ public static void main (String [] args ) throws Exception {
6+
7+ Philosopher [] philosophers = new Philosopher [5 ];
8+ Object [] forks = new Object [philosophers .length ];
9+
10+ for (int i = 0 ; i < forks .length ; i ++) {
11+ forks [i ] = new Object ();
12+ }
13+
14+ for (int i = 0 ; i < philosophers .length ; i ++) {
15+
16+ Object leftFork = forks [i ];
17+ Object rightFork = forks [(i + 1 ) % forks .length ];
18+
19+ if (i == philosophers .length - 1 ) {
20+ philosophers [i ] = new Philosopher (rightFork , leftFork ); // The last philosopher picks up the right fork first
21+ } else {
22+ philosophers [i ] = new Philosopher (leftFork , rightFork );
23+ }
24+
25+ Thread t = new Thread (philosophers [i ], "Philosopher " + (i + 1 ));
26+ t .start ();
27+ }
28+ }
29+ }
Original file line number Diff line number Diff line change 1+ package com .baeldung .concurrent .diningphilosophers ;
2+
3+ public class Philosopher implements Runnable {
4+
5+ private final Object leftFork ;
6+ private final Object rightFork ;
7+
8+ public Philosopher (Object left , Object right ) {
9+ this .leftFork = left ;
10+ this .rightFork = right ;
11+ }
12+
13+ private void doAction (String action ) throws InterruptedException {
14+ System .out .println (Thread .currentThread ().getName () + " " + action );
15+ Thread .sleep (((int ) (Math .random () * 100 )));
16+ }
17+
18+ @ Override public void run () {
19+ try {
20+ while (true ) {
21+ doAction (System .nanoTime () + ": Thinking" ); // thinking
22+ synchronized (leftFork ) {
23+ doAction (System .nanoTime () + ": Picked up left fork" );
24+ synchronized (rightFork ) {
25+ doAction (System .nanoTime () + ": Picked up right fork - eating" ); // eating
26+ doAction (System .nanoTime () + ": Put down right fork" );
27+ }
28+ doAction (System .nanoTime () + ": Put down left fork. Returning to thinking" );
29+ }
30+ }
31+ } catch (InterruptedException e ) {
32+ Thread .currentThread ().interrupt ();
33+ return ;
34+ }
35+ }
36+ }
You can’t perform that action at this time.
0 commit comments