-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathAtomicIntegerTest.java
More file actions
50 lines (40 loc) · 1.14 KB
/
AtomicIntegerTest.java
File metadata and controls
50 lines (40 loc) · 1.14 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
package concurrency;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.*;
/**
* RUN:
* javac concurrency/AtomicIntegerTest.java && java concurrency.AtomicIntegerTest
*
* OUTPUT:
*
*/
public class AtomicIntegerTest implements Runnable {
private AtomicInteger i = new AtomicInteger(0);
public int getValue() { return i.get(); }
private void evenIncrement() { i.addAndGet(2); }
public void run() {
while (true) {
evenIncrement();
}
}
public static void main(String[] args) {
// end through 5 seconds
new Timer().schedule(new TimerTask() {
public void run() {
System.err.println("Aborting");
System.exit(0);
}
}, 5000);
ExecutorService exec = Executors.newCachedThreadPool();
AtomicIntegerTest ait = new AtomicIntegerTest();
exec.execute(ait);
while (true) {
int val = ait.getValue();
if (val % 2 != 0) {
System.out.println(val);
System.exit(0);
}
}
}
}