-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAtomicExample.java
39 lines (28 loc) · 1004 Bytes
/
AtomicExample.java
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
package com.tamco.concurrency;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Created by TamCO on 2/12/18.
*/
public class AtomicExample {
private static final int LOOP = 100000;
private static AtomicInteger resource = new AtomicInteger(10);
public static void main(String[] args) throws InterruptedException {
Runnable increase = () -> {
for (int i = 0; i < LOOP; i++) {
resource.getAndIncrement();
}
};
Runnable decrease = () -> {
for (int i = 0; i < LOOP; i++) {
resource.getAndDecrement();
}
};
Thread increaseThread = new Thread(increase);
Thread decreaseThread = new Thread(decrease);
increaseThread.start();
decreaseThread.start();
increaseThread.join();
decreaseThread.join();
System.out.println("After several increments and decrements the resource is still: " + resource.intValue());
}
}