|
|
@@ -13,6 +13,40 @@ public class Philosopher implements Runnable{ |
|
|
|
|
|
|
|
@Override |
|
|
|
public void run(){ |
|
|
|
while(true) { |
|
|
|
allocateForks(); |
|
|
|
System.out.println("Philosopher " + id + " is eating"); |
|
|
|
try{ |
|
|
|
Thread.sleep(2000); |
|
|
|
}catch (Exception e){ |
|
|
|
|
|
|
|
} |
|
|
|
left.put(); |
|
|
|
right.put(); |
|
|
|
System.out.println("Philosopher " + id + " finished eating"); |
|
|
|
|
|
|
|
|
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
protected void allocateForks() { |
|
|
|
Fork firstFork, secondFork; |
|
|
|
|
|
|
|
if (left.getId() < right.getId()){ |
|
|
|
firstFork = left; |
|
|
|
secondFork = right; |
|
|
|
} else { |
|
|
|
firstFork = right; |
|
|
|
secondFork = left; |
|
|
|
} |
|
|
|
|
|
|
|
System.out.println("Philosopher " + id + " is trying to take Fork " + firstFork.getId()); |
|
|
|
while (!firstFork.take()) |
|
|
|
Thread.yield(); |
|
|
|
System.out.println("Philosopher " + id + " got Fork " + firstFork.getId()); |
|
|
|
System.out.println("Philosopher " + id + " is trying to take Fork " + secondFork.getId()); |
|
|
|
while (!secondFork.take()) |
|
|
|
Thread.yield(); |
|
|
|
System.out.println("Philosopher " + id + " got Fork " + secondFork.getId()); |
|
|
|
} |
|
|
|
} |