-
Notifications
You must be signed in to change notification settings - Fork 24
/
Worker.java
40 lines (35 loc) · 1.11 KB
/
Worker.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
package jpz.puzzle77;
import java.util.*;
public class Worker extends Thread {
private volatile boolean quittingTime = false;
public void run() {
while (!quittingTime)
pretendToWork();
System.out.println("Beer is good");
}
private void pretendToWork() {
try {
Thread.sleep(300); // Sleeping on the job?
} catch (InterruptedException ex) { }
}
// It's quitting time, wait for worker - Called by good boss
synchronized void quit() throws InterruptedException {
quittingTime = true;
join();
}
// Rescind quitting time - Called by evil boss
synchronized void keepWorking() {
quittingTime = false;
}
public static void main(String[] args)
throws InterruptedException {
final Worker worker = new Worker();
worker.start();
Timer t = new Timer(true); // Daemon thread
t.schedule(new TimerTask() {
public void run() { worker.keepWorking(); }
}, 500);
Thread.sleep(400);
worker.quit();
}
}