-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAlternateStop.java
More file actions
46 lines (36 loc) · 862 Bytes
/
Copy pathAlternateStop.java
File metadata and controls
46 lines (36 loc) · 862 Bytes
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
package threadbook.ch05;
public class AlternateStop extends Object implements Runnable {
private volatile boolean stopRequested;
private Thread runThread;
public void run() {
runThread = Thread.currentThread();
stopRequested = false;
int count = 0;
while ( !stopRequested ) {
System.out.println("Running ... count=" + count);
count++;
try {
Thread.sleep(300);
} catch ( InterruptedException x ) {
Thread.currentThread().interrupt(); // re-assert interrupt
}
}
}
public void stopRequest() {
stopRequested = true;
if ( runThread != null ) {
runThread.interrupt();
}
}
public static void main(String[] args) {
AlternateStop as = new AlternateStop();
Thread t = new Thread(as);
t.start();
try {
Thread.sleep(2000);
} catch ( InterruptedException x ) {
// ignore
}
as.stopRequest();
}
}