My favorites | Sign in
Project Home Downloads Wiki Issues Source
READ-ONLY: This project has been archived. For more information see this post.
Search
for
  Advanced search   Search tips   Subscriptions

Issue 7 attachment: Worker.java (1.1 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
package puzzler;

import java.util.Timer;
import java.util.TimerTask;
//use Runnable rather than extending thread
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);
}catch(InterruptedException e){}
}
/*synchronized void quit() throws InterruptedException{
quittingTime = true;
join();
}
synchronized void keepWorking(){
quittingTime = false;
}*/

private final Object lock = new Object();
void quit() throws InterruptedException{
synchronized(lock){
quittingTime = true;
join();
}
}

void keepWorking(){
synchronized(lock){
quittingTime = false;
}
}

static void main() throws InterruptedException{
final Worker worker = new Worker();
worker.start();
Timer t = new Timer(true);
t.schedule(new TimerTask(){
public void run(){
worker.keepWorking();
}
}, 500);
Thread.sleep(400);
worker.quit();
}
}
Powered by Google Project Hosting