-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathStopThread.java
More file actions
31 lines (25 loc) · 809 Bytes
/
StopThread.java
File metadata and controls
31 lines (25 loc) · 809 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
package ej2.item66.fix1;
// Properly synchronized cooperative thread termination - Page 261
import java.util.concurrent.*;
public class StopThread {
private static boolean stopRequested;
private static synchronized void requestStop() {
stopRequested = true;
}
private static synchronized boolean stopRequested() {
return stopRequested;
}
public static void main(String[] args)
throws InterruptedException {
Thread backgroundThread = new Thread(new Runnable() {
public void run() {
int i = 0;
while (!stopRequested())
i++;
}
});
backgroundThread.start();
TimeUnit.SECONDS.sleep(1);
requestStop();
}
}