-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPerson.java
More file actions
98 lines (89 loc) · 2.87 KB
/
Person.java
File metadata and controls
98 lines (89 loc) · 2.87 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
94
95
96
97
98
package newLessons.lessonEleven;
import java.util.Random;
public class Person implements Runnable {
private static final Random r = (new Random());
private static final int SLEEPTIME = 5000;
private static final int BATHROOMTIME = 1500;
private String name;
private boolean bedroomPreference;
private House theHouse;
public Person(String name, House theHouse) {
this.name = name;
this.bedroomPreference = r.nextBoolean();
this.theHouse = theHouse;
}
@Override
public void run() {
for (int runCount = 0; runCount < 15; runCount++) {
if (runCount == 0) {
theHouse.isFrontDoorOpen.set(true);
} else if (runCount == 1) {
theHouse.isFrontDoorOpen.set(false);
} else {
if (r.nextBoolean()) {
// Here you can see that the person will try both rooms and if neither is open it will wait for it's preference.
// Once obtaining a room they sleep (literally) for a random amount of time and then unlock the room.
if (theHouse.bedroomOne.tryLock()) {
try {
System.out.println(name + " is going to sleep!");
Thread.sleep(r.nextInt(SLEEPTIME));
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println(name + " is awake!");
theHouse.bedroomOne.unlock();
}
} else {
if (theHouse.bedroomTwo.tryLock()) {
try {
System.out.println(name + " is going to sleep!");
Thread.sleep(r.nextInt(SLEEPTIME));
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println(name + " is awake!");
theHouse.bedroomTwo.unlock();
}
} else {
if (bedroomPreference) {
theHouse.bedroomOne.lock();
try {
System.out.println(name + " is going to sleep!");
Thread.sleep(r.nextInt(SLEEPTIME));
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println(name + " is awake!");
theHouse.bedroomOne.unlock();
}
} else {
theHouse.bedroomTwo.lock();
try {
System.out.println(name + " is going to sleep!");
Thread.sleep(r.nextInt(SLEEPTIME));
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println(name + " is awake!");
theHouse.bedroomTwo.unlock();
}
}
}
}
} else {
// The bathroom is much simpler just involving a simple lock and then release after a random amount of time.
theHouse.bathroom.lock();
try {
System.out.println(name + " is going to the bathroom!");
Thread.sleep(r.nextInt(BATHROOMTIME));
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println(name + " is done in the bathroom!");
theHouse.bathroom.unlock();
}
}
}
}
}
}