-
Notifications
You must be signed in to change notification settings - Fork 0
/
Philosopher.java
74 lines (64 loc) · 1.5 KB
/
Philosopher.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package com.griddymanics.threads.philosophers;
import java.util.Random;
public class Philosopher implements Runnable {
private final int id;
private final Fork leftFork;
private final Fork rightFork;
public Philosopher(int id, Fork leftFork, Fork rightFork) {
this.id = id;
this.leftFork = leftFork;
this.rightFork = rightFork;
}
public void run() {
boolean isInterupted = false;
while (!isInterupted) {
if (checkAvailableResources()) {
startEating();
finishEating();
} else {
try {
Thread.sleep(new Random().nextInt(5));
} catch (InterruptedException e) {
e.printStackTrace();
isInterupted = true;
}
}
}
}
private boolean checkAvailableResources() {
if (!leftFork.isOccupied()) {
leftFork.occupy();
if (!rightFork.isOccupied()) {
rightFork.occupy();
return true;
} else {
leftFork.free();
return false;
}
}
return false;
}
private void startEating() {
System.out.printf("Philosopher %d starts eating\n", id);
try {
Thread.sleep(new Random().nextInt(50));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void finishEating() {
rightFork.free();
leftFork.free();
System.out.printf("Philosopher %d ends eating\n", id);
try {
Thread.sleep(new Random().nextInt(50));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public String toString() {
return "Philosopher [id=" + id + ", leftFork=" + leftFork
+ ", rightFork=" + rightFork + "]";
}
}