-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPhilosophers.java
More file actions
93 lines (81 loc) · 2.03 KB
/
Copy pathPhilosophers.java
File metadata and controls
93 lines (81 loc) · 2.03 KB
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package myDiningPhilosopher;
import java.util.Random;
import java.util.concurrent.locks.Lock;
public class Philosophers implements Runnable
{
private final int id;
private final Lock leftChopstick;
private final Lock rightChopstick;
private Random random = new Random();
public Philosophers(int id, Lock leftChopstick, Lock rightChopstick)
{
this.id = id + 1;
this.leftChopstick = leftChopstick;
this.rightChopstick = rightChopstick;
}
public void run()
{
try
{
while(true)
{
think();
pickUpLeftChopstick();
pickUpRightChopstick();
eat();
putDownChopsticks();
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
private void think()
{
System.out.println("Philsopher " + id + " is thinking...");
try {
Thread.sleep(random.nextInt(1500));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void pickUpLeftChopstick() throws InterruptedException
{
leftChopstick.lock();
System.out.println("Philosopher " + id + " picked up the left Chopstick.");
long begin = System.currentTimeMillis();
/*
while(rightChopstick.tryLock() == false)
{
if(rightChopstick.tryLock() == true)
{pickUpRightChopstick();}
long end = System.currentTimeMillis();
if(end - begin == 5000)
{
leftChopstick.unlock();
System.out.println("Philosopher " + id + " timed out and dropped his Chopstick.");
Thread.sleep(random.nextInt(750));
run();
}
} */
}
private void pickUpRightChopstick()
{
rightChopstick.lock();
System.out.println("Philosopher " + id + " picked up the right Chopstick.");
}
private void eat() throws InterruptedException
{
System.out.println("Philosopher " + id + " is now eating. Yum");
Thread.sleep(random.nextInt(1000)+1000);
}
private void putDownChopsticks() throws InterruptedException
{
leftChopstick.unlock();
rightChopstick.unlock();
System.out.println("Philosopher " + id + " finished eating.");
Thread.sleep(random.nextInt(1000)+1500);
}
}