-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGameThread.java
More file actions
78 lines (59 loc) · 1.74 KB
/
GameThread.java
File metadata and controls
78 lines (59 loc) · 1.74 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
package thread;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import main.Main;
import assets.AssetContainer;
public abstract class GameThread extends Thread implements ObservableThread {
protected Main mainApplication;
/** Everything must need to know about the assets. */
protected AssetContainer assContainer;
/** List of listeners that care about when the initial setup is complete. */
private List<ThreadObserver> setupObservers = new ArrayList<ThreadObserver>();
/** Flag to determine when to stop the loop. */
protected boolean timeToStop = false;
/**
* A CyclicBarrier which pauses each thread at the end of an iteration,
* until the other threads are ready for the next iteration.
*/
private CyclicBarrier barrier;
public GameThread(AssetContainer assContainer, Main mainApplication, CyclicBarrier barrier) {
this.assContainer = assContainer;
this.mainApplication = mainApplication;
this.barrier = barrier;
}
public void stopThread() {
timeToStop = true;
}
public void run() {
setup();
while (!timeToStop) {
gameLoop();
try {
barrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
afterLoop();
}
}
afterLoop();
}
protected void beforeLoop() {
// No default functionality.
}
protected void afterLoop() {
// No default functionality.
}
protected abstract void gameLoop();
protected void setup() {
beforeLoop();
// Notify observers that setup is complete.
for (ThreadObserver observer : setupObservers) {
observer.setupDone(this);
}
}
public void registerSetupObserver(ThreadObserver observer) {
setupObservers.add(observer);
}
}