forked from Apress/functional-interfaces-in-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShareAnInt.java
More file actions
44 lines (42 loc) · 1.29 KB
/
ShareAnInt.java
File metadata and controls
44 lines (42 loc) · 1.29 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
package chapter14;
import java.util.concurrent.atomic.*;
import java.util.concurrent.*;
public class ShareAnInt
{
public static void main(String[] args)
{
AtomicInteger num = new AtomicInteger(0);
CompletableFuture<Integer> cf1 =
CompletableFuture.supplyAsync( () -> {
int x = num.get();
for (int i=0; i<20; ++i)
{
x = num.updateAndGet(z -> z + 10);
if (num.compareAndSet(100, 0))
{
System.out.println("cf1 resets atomic variable");
x = num.get();
}
System.out.println("cf1 a = " + x);
}
return x;
});
CompletableFuture<Integer> cf2 =
CompletableFuture.supplyAsync( () -> {
int x = num.get();
for (int i=0; i<20; ++i)
{
x = num.updateAndGet(z -> z + 10);
if (num.compareAndSet(80, 0))
{
System.out.println("cf2 resets atomic variable");
x = num.get();
}
System.out.println("cf2 a = " + x);
}
return x;
});
CompletableFuture.allOf(cf1,cf2)
.join();
}
}