-
Notifications
You must be signed in to change notification settings - Fork 1
/
AtomicDemo.java
72 lines (66 loc) · 2.36 KB
/
AtomicDemo.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerArray;
import java.util.concurrent.atomic.AtomicLong;
// atomic (пакет java.util.concurrent.atomic)
// ------------------------------------------
// Классы из пакета java.util.concurrent.atomic обеспечивают
// выполнение атомарных операций
/**
* AtomicInteger
*/
//-->
public class AtomicDemo {
static final Object LOCK = new Object();
static final AtomicInteger ATOMIC_SUM = new AtomicInteger();
static final CountDownLatch CDL = new CountDownLatch(100000);
static int sum = 0;
static volatile int globalI;
static int threadCount = 0;
static {
AtomicInteger atomicInteger = new AtomicInteger(2);
AtomicLong atomicLong = new AtomicLong(3232L);
AtomicBoolean atomicBoolean = new AtomicBoolean(true);
// Нет: AtomicByte, AtomicShort, AtomicFloat, AtomicDouble, AtomicString
AtomicIntegerArray atomicIntegerArray = new AtomicIntegerArray(new int[]{1, 3, 4});
atomicInteger.addAndGet(10);
atomicBoolean.set(true);
atomicBoolean.get();
atomicLong.addAndGet(100000);
atomicIntegerArray.addAndGet(1, 10);
}
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 1000; i++) {
Thread thread = new MyThread();
thread.start();
}
System.out.println("sum = " + sum);
System.out.println("ATOMIC_SUM = " + ATOMIC_SUM.get());
System.out.println("globalI = " + globalI);
System.out.println("wait");
Thread.sleep(500);
CDL.await();
System.out.println("threadCount = " + threadCount);
System.out.println("sum = " + sum);
System.out.println("ATOMIC_SUM = " + ATOMIC_SUM.get());
}
private static void inc() {
synchronized (LOCK) {
sum++;
}
}
private static class MyThread extends Thread {
@Override
public void run() {
threadCount++;
for (int i = 0; i < 100; ++i) {
globalI++;
inc();
ATOMIC_SUM.incrementAndGet();
CDL.countDown();
}
}
}
}
//<--