-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExample113.java
More file actions
34 lines (29 loc) · 1.05 KB
/
Example113.java
File metadata and controls
34 lines (29 loc) · 1.05 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
// Example 113 from page 87
//
import java.io.IOException;
class Example113 {
public static void main(String[] args) throws IOException {
final MutableInteger mi = new MutableInteger();
Thread t = new Thread(new Runnable() {
public void run() {
while (mi.get() == 0) // Loop while zero
{ }
System.out.println("I completed, mi = " + mi.get());
}
});
t.start();
System.out.println("Press Enter to set mi to 42 and stop the loop:");
System.in.read(); // Wait for enter key
mi.set(42);
System.out.println("mi set to 42, waiting for thread ...");
try { t.join(); } catch (InterruptedException exn) { }
System.out.println("Thread t completed, and so does main");
}
}
// From Goetz et al p. 36. WARNING: Useless without "volatile" or
// "synchronized" to ensure visibility of writes across threads.
class MutableInteger {
private /* volatile */ int value = 0;
public void set(int value) { this.value = value; }
public int get() { return value; }
}