-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPlayer.java
More file actions
90 lines (70 loc) · 2.17 KB
/
Player.java
File metadata and controls
90 lines (70 loc) · 2.17 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
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
public class Player implements Runnable {
private final String text;
private final Lock lock;
private final Condition myTurn;
private final CountDownLatch entryBarrier;
private final CountDownLatch exitBarrier;
private Condition nextTurn;
private Player nextPlayer;
private volatile boolean play = false;
public Player(String text,
Lock lock,
CountDownLatch entryBarrier,
CountDownLatch exitBarrier) {
this.text = text;
this.lock = lock;
this.myTurn = lock.newCondition();
this.entryBarrier = entryBarrier;
this.exitBarrier = exitBarrier;
}
@Override
public void run() {
if(entryBarrierOpen())
play();
}
public boolean entryBarrierOpen() {
try {
entryBarrier.await();
return true;
} catch (InterruptedException e) {
System.out.println("Player "+text+
" was interrupted before starting Game!");
return false;
}
}
public void exitBarrierAwait() {
try {
exitBarrier.await();
} catch (InterruptedException e) {
System.out.println("Player "+text+
" was interrupted before finishing Game!");
}
}
private void play() {
while (!Thread.interrupted()) {
lock.lock();
try {
while (!play)
myTurn.awaitUninterruptibly();
System.out.println(text);
this.play = false;
nextPlayer.play = true;
nextTurn.signal();
} finally {
lock.unlock();
}
}
exitBarrier.countDown();
}
public void setNextPlayer(Player nextPlayer) {
this.nextPlayer = nextPlayer;
this.nextTurn = nextPlayer.myTurn;
}
public void setPlay(boolean play) {
this.play = play;
}
}